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.
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]
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With