val name: String, | val birthDate: LocalDate, | ): | def age(now: LocalDate): Int = ChronoUnit.YEARS .between(birthDate, now).toInt // defined case class Person scala> val 🐬 = Person("lagénorhynque", LocalDate.of(1990, 1, 18)) val 🐬: Person = Person(lagénorhynque,1990-01-18) scala> 🐬.name val res0: String = lagénorhynque scala> 🐬.age(LocalDate.now) val res1: Int = 35 7
for // Range (Seq) 型の場合 | x <- 1 to 3 | y <- 4 to 5 | yield x * y // => 1*4, 1*5, 2*4, 2*5, 3*4, 3*5 val res0: IndexedSeq[Int] = Vector(4, 5, 8, 10, 12, 15) scala> for // Option 型(Kotlin ではnullable type で表すもの) の場合 | x <- Some(2) | y <- Some(3) | yield x * y // => Some(2*3) val res1: Option[Int] = Some(6) scala> for | x <- Some(2) | y <- None: Option[Int] | yield x * y // => 全体としてNone に val res2: Option[Int] = None Haskell のdo 記法 14
書籍FP in Scala のサンプルコードより引用 | case Leaf(value: A) | case Branch(left: Tree[A], right: Tree[A]) | | def depth: Int = this match | case Leaf(_) => 0 | case Branch(l, r) => 1 + (l.depth.max(r.depth)) // defined class Tree scala> import Tree._ scala> Branch(Leaf("a"), Branch(Branch(Leaf("b"), Leaf("c")) , Leaf("d"))).depth val res0: Int = 3 15