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

3 Answers 3

18

Use the apply method, it returns directly the String and throws a NoSuchElementException if the key is not found:

scala> import scala.collection.mutable.LinkedHashMap
import scala.collection.mutable.LinkedHashMap

scala> val map = new LinkedHashMap[String,String]
map: scala.collection.mutable.LinkedHashMap[String,String] = Map()

scala> map.put("City","Dallas")
res2: Option[String] = None

scala> map("City")
res3: String = Dallas
Sign up to request clarification or add additional context in comments.

1 Comment

apply is a magic method that gets called if you 'call' an object. map("City") is equivalent to map.apply("City").
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.

4 Comments

Thanks for the reply. But how to make it output just the value instead of Some(value) ?
@Tom I have just add one example of how to use it.
@Tom: You could just use map("City").
Related post on better alternative to map.get().get - stackoverflow.com/questions/19969225/…
2

There are two more ways you can handle Option results.

You can pattern match them:

scala> map.get("City") match {
 |   case Some(value) => println(value)
 |   case _ => println("found nothing")
 | }
Dallas

Or there is another neat approach that appears somewhere in Programming in Scala. Use foreach to process the result. If a result is of type Some, then it will be used. Otherwise (if it's None), nothing happens:

scala> map.get("City").foreach(println)
Dallas

scala> map.get("Town").foreach(println)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.