Why do these two checks for null and empty return different results?

Can someone explain how I can check if a String is empty or empty?

I have the code below that gives different results. 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

 s.isEmpty() : true someMap.get("key1") : false 

But why?

+4
source share
4 answers

This is due to the fact that Map.get returns Option : either Some(value) if the value is on the map or None if there is no such key in the Map.

If you turn Some("") into a string, you will get "Some()" , which is definitely not empty.

To achieve the desired behavior, write your code as

 someMap("key1").toString.isEmpty 
+10
source

I suppose that

 val someMap = ListMap[String,String]("key1" -> "") 

is a typo, and you really meant:

 val someMap = Map[String,String]("key1" -> "") 

The reason you get different results is because get(key) on maps returns Option . If the specified key is stored in Map , calling map.get(key) returns Some(<value_for_given_key>) . If this key is not stored in Map , calling map.get(key) returns None .

In your example, you store the value "with the key" key1 "in someMap . Therefore, if you call someMap.get("key1") , you get Some("") . Then you call toString on that value, which returns "Some()" . And "Some()".isEmpty() returns false for obvious reasons.

+2
source

As noted, the ListMap.get method that you call returns a parameter wrapped around your string:

 def get(key: A): Option[B] 

Try this enhanced println statement to see the actual result:

 println("someMap.get(\"key1\") : "+someMap.get("key1")) 

Using an IDE such as Intellij free Idea 12 CE can help you identify such problems earlier by showing the method signature and providing suggestions for completing the code for the return value.

0
source

I check null and empty using the code below to avoid a blank map error.

 /** * isContain() will check is the key value is present in map or not and the value is null or Empty * @Parameters : String * @return : Boolean */ def isContain(paramName : String,params : scala.collection.immutable.ListMap[String,String]) : Boolean = { if(!(params.contains(paramName))) return false !isNullOrEmpty(params(paramName)) } /** * isNullOrEmpty() will check is the String null or Empty * @Parameters : String * @return : Boolean */ def isNullOrEmpty(paramVal : String): Boolean = { if(paramVal == null || paramVal.isEmpty()) return true return false } 
0
source

All Articles