Alex Rivera | Logout

Problem with outputting map values in scala

Asked 2011-06-17T11:56:07.547
11

I have the following code snippet:

val map = new LinkedHashMap[String,String]
map.put("City","Dallas")
println(map.get("City"))

This outputs Some(Dallas) instead of just Dallas. Whats the problem with my code ?

Thank You

Edit
Report

1 Answer

13

It's not really a problem.

While Java's Map version uses null to indicate that a key don't have an associated value, Scala's Map[A,B].get returns a Options[B], which can be Some[B] or None, and None plays a similar role to java's null.

REPL session showing why this is useful:

scala> map.get("State")
res6: Option[String] = None

scala> map.get("State").getOrElse("Texas")
res7: String = Texas

Or the not recommended but simple get:

scala> map.get("City").get
res8: String = Dallas

scala> map.get("State").get
java.util.NoSuchElementException: None.get
        at scala.None$.get(Option.scala:262)

Check the Option documentation for more goodies.

answered 2011-06-17T12:02:23.520

Your Answer