2016-02-26 8 views
6

Wenn ich schaffen ein Option[Map[String,String]] wie diesesWie funktioniert `.get ("Schlüssel")` auf `Option [Map [String, String]]` Arbeit

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

Warum diesen Aufruf funktionierts:

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

Da x ist die Instanz Option und es gibt keine Methode get, die Parameter auf den case class Some akzeptiert und diese Klasse ist endgültig, soll dies nicht funktionieren. Die IDE gibt keine Hinweise, warum das funktioniert.

+1

Es ruft die Methode apply auf Karte – hasumedic

Antwort

11

Option hat eine get Methode, die keine Parameter-Liste. Sie nennen es nur um den Namen mit get ohne Argument Liste:

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) 

Was Sie zurück bekommen, natürlich, die Map.

Die ("foo") nach get wird auf die Map angewendet. Beachten Sie, dass dies eine Abkürzungssyntax zum Aufrufen der apply-Methode auf der Map ist. So entspricht x.get("foo")x.get.apply("foo").

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

scala> x.get.apply("foo") // For this 
res3: String = bar 
Verwandte Themen