Could anyone please explain how can I check if String is null or empty?
I have a below code which is giving different result explain why.
val someMap = ListMap[String,String]("key1" -> "")
val s = ""
println("s.isEmpty() : "+s.isEmpty())
println("someMap.get(\"key1\") : "+someMap.get("key1").toString().isEmpty)
Result is
s.isEmpty() : true
someMap.get("key1") : false
But why?
This is because Map.get returns an Option: either Some(value) if the value is in the Map or None, if there is no such key in Map.
If you turn Some("") to a string you'll get "Some()" which is definitely not empty.
To achieve the behavior you wanted, write your code as
someMap("key1").toString.isEmpty
i assume the
val someMap = ListMap[String,String]("key1" -> "")
is a typo and you actually meant:
val someMap = Map[String,String]("key1" -> "")
The reason you get different results is that get(key) on maps returns Option. If given key is stored in a Map, calling map.get(key) returns Some(<value_for_given_key>). If the given key is not stored in a Map, calling map.get(key) returns None.
In your example, you store value "" with key "key1" into someMap. Therefore, if you call someMap.get("key1"), you get Some(""). You then call toString on that value, which returns "Some()". And "Some()".isEmpty() returns false for obvious reasons.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With