Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does `.get("key")` on a `Option[Map[String,String]]` work

Tags:

scala

When I create an Option[Map[String,String]] like this

scala> val x = Some(Map("foo" -> "bar"))
x: Some[scala.collection.immutable.Map[String,String]] = Some(Map(foo -> bar))

Why does this call work:

scala> x.get("foo")
res0: String = bar

Since x is of instance Option and there is no method get that accepts parameters on the case class Some and that class is final, this should not work. The IDE is not giving any hints, why this works.

like image 221
mana Avatar asked Feb 26 '16 14:02

mana


People also ask

What is .get in Scala?

Scala Map get() method with example The get() method is utilized to give the value associated with the keys of the map. The values are returned here as an Option i.e, either in form of Some or None. Method Definition:def get(key: A): Option[B]

How do you add a string value to a string map?

To insert the data in the map insert() function in the map is used. It is used to insert elements with a particular key in the map container.

What is map string string in Scala?

A map represents an mapping from keys to values. The Scala Map type has two type parameters, for the key type and for the value type. So a Map[String, Int] maps strings to integers, while a Map[Int, Set[String]] maps integers to sets of strings. Scala provides both immutable and mutable maps.


1 Answers

Option has a get method that has no parameter list. You call it by just using the name get without an argument list:

scala> val x = Some(Map("foo" -> "bar"))
x: Some[scala.collection.immutable.Map[String,String]] = Some(Map(foo -> bar))

scala> x.get  // Note: no arguments
res0: scala.collection.immutable.Map[String,String] = Map(foo -> bar)

What you get back is, obviously, the Map.

The ("foo") after get is applied to the Map. Note that this is shortcut syntax for calling the apply method on the Map. So, x.get("foo") is equivalent to x.get.apply("foo").

scala> x.get("foo")  // Shortcut syntax
res2: String = bar

scala> x.get.apply("foo")  // For this
res3: String = bar
like image 125
Jesper Avatar answered Oct 04 '22 09:10

Jesper