Scala – How to access value of map with a key if key was not found in scala

scala

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?

Best Solution

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)
Related Question