Assume I have
var mp = Map[String,String]()
.....
val n = mp("kk")
The above will throw runtime error in case key "kk" did not exist.
I expected n will be null in case key did not exist. I want n to be null if key did not exist.
What is the proper way to handle this situation in scala with a short code sample?
First of all, you probably don't really want null, as that's almost always a sign of bad coding in Scala. What you want is for n to be of type Option[String], which says that the value is either a String or is missing. The right way to do that is with the .get() method on you map
val n = mp.get("kk")
If you really do need null (for interop with Java libraries, for example), you can use .getOrElse()
val n = mp.getOrElse("kk", null)
Try this:
val valueOpt = mp.get("kk")
Your result is of type Option[String]
and can be either None
or Some(actualValue)
. You can use pattern matching to find out:
valueOpt match {
case Some(value) => println(value)
case None => println("default")
}
A more appropriate way to do that kind of things, however, is to use the methods on Option
, e.g.:
println(valueOpt.getOrElse("default"))
Look for the API docs for Option
there.
Edit: Note that Map
itself directly defines a getOrElse
method, too, as shown in Dave's answer.
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