読者です 読者をやめる 読者になる 読者になる

by shigemk2

当面は技術的なことしか書かない

ScalaのMapやり直し

Scala

Mapの操作。

$ scala
Welcome to Scala version 2.9.2 (OpenJDK 64-Bit Server VM, Java 1.7.0_55).
Type in expressions to have them evaluated.
Type :help for more information.

scala> Map(1 -> "a", 2 -> "b", 3 -> "c") get (1)
res0: Option[java.lang.String] = Some(a)

scala> Map(1 -> "a", 2 -> "b", 3 -> "c") get (1)
res1: Option[java.lang.String] = Some(a)

scala> Map(1 -> "a", 2 -> "b", 3 -> "c") (1)
res2: java.lang.String = a

scala> Map(1 -> "a", 2 -> "b", 3 -> "c") getOrElse (1, "d")
res3: java.lang.String = a

scala> Map(1 -> "a", 2 -> "b", 3 -> "c") getOrElse (4, "d")
res4: java.lang.String = d

scala> Map(1 -> "a", 2 -> "b", 3 -> "c") isDefineAt (1)
<console>:8: error: value isDefineAt is not a member of scala.collection.immutable.Map[Int,java.lang.String]
              Map(1 -> "a", 2 -> "b", 3 -> "c") isDefineAt (1)
                                                ^

scala> Map(1 -> "a", 2 -> "b", 3 -> "c") isDefinedAt (1)
res6: Boolean = true

scala> Map(1 -> "a", 2 -> "b", 3 -> "c") isDefinedAt (4)
res7: Boolean = false