Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with outputting map values in scala

Tags:

scala

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

like image 568
Tom Avatar asked Jun 17 '11 11:06

Tom


People also ask

What is map function in Scala?

Scala Map Function also is known as HASH TABLE is a collection of Key/Value pairs called as Hash Tables. The Key is used to access the values associated with it. Values in a Map can be the same but keys are always unique.

How do you know if a map is empty Scala?

isEmpty: This Scala map method returns true if the map is empty otherwise this returns false. Values can be accessed using Map variable name and key. If we try to access value associated with the key “John”, we will get an error because no such key is present in the Map.

What is the difference between isempty and values in Scala map?

values: Value method returns an iterable containing each value in the Scala map. isEmpty: This Scala map method returns true if the map is empty otherwise this returns false. Values can be accessed using Map variable name and key.

How do you map a mutable variable in Scala?

// Mutable variable = scala.collection.mutable.Map (key_1 -> value_1, key_2 -> value_2, key_3 -> value_3, ....) There are three basic operations we can carry out on a Map: keys: In Scala Map, This method returns an iterable containing each key in the map.


2 Answers

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
like image 164
michael.kebe Avatar answered Feb 17 '23 04:02

michael.kebe


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.

like image 22
pedrofurla Avatar answered Feb 17 '23 04:02

pedrofurla