Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 841
rjc Avatar asked Sep 12 '25 16:09

rjc


2 Answers

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)
like image 52
Dave Griffith Avatar answered Sep 14 '25 11:09

Dave Griffith


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 Mapitself directly defines a getOrElse method, too, as shown in Dave's answer.

like image 41
Jean-Philippe Pellet Avatar answered Sep 14 '25 12:09

Jean-Philippe Pellet