I understand
- in Scala use of null should be avoided
- and Map.get will return a Option[B] and I can use .getOrElse to get the value and fallback to a default value
e.g.
map.getOrElse("key1","default")
Meanwhile I am interacting with a Java library, which some values are null.
e.g. Map("key1"->null)
getOrElse
will throw null pointer in this case.
I want to handle both cases and result in writing something like this
def getOrElseNoNull[A,B](map:Map[A,B],key:A,default:B) = {
map.get(key) match{
case Some(x) if x != null => x
case _ => default
}
}
which is quite ugly. (it is Map[Any] and I need a string from that key)
getOrElseNoNull(map,"key1","").asInstanceOf[String])
is it possible to use implicit to extend the map, or any other elegant way?