Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this two checks for null and empty returns different results?

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?

like image 246
Azhar Avatar asked Dec 15 '22 16:12

Azhar


2 Answers

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
like image 89
om-nom-nom Avatar answered Feb 15 '23 11:02

om-nom-nom


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.

like image 21
Arg Avatar answered Feb 15 '23 10:02

Arg