user2895589 user2895589 - 3 months ago 8
Scala Question

How to use getOrElse with Map and compare value in scala

I have parsed JSON to a Map[String , Any].In JSON I have a hasHeader optional field.

{
hasHeader : "Y" (optional member)

}


I want to check

If(jsonMap.get("hasHeader") <=> "Y")
doSome()
else
Nothing


As hadHeader is optional it is safe to use getOrElse but how do I use getOrElse and compare value with "Y" in scala.

One way I can think of is:

if(!jsonMap.get("hasHeader").isEmpty) {
val hasHeaderVal = jsonMap.get("hasHeader")

if( hasHeaderVal.equals("Y")){
doSomething()
}
}


Is there any better way of doing this?

Answer

You are looking for the following:

jsonMap.get("hasHeader").map(_ == "Y").getOrElse(false)

The way .map works for Options is that it only applies the given function if the value is a Some (otherwise the None just passes through). Then, .getOrElse gets the value if the Option it is called on is a Some but otherwise returns its first argument (sort of a default backup).