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

Viewed 43231

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?

3 Answers
val conversionRatios:mutable.Map[String, Double] = mutable.Map[String, Double](
    "USD" -> 2.0,
    "CNY" -> 3.0
  )

val currentRate = conversionRatios.apply(key) // it will return you value or NoSuchElementException will be thrown
Related