A sequence of cases (i.e., alternatives) in curly braces can be used anywhere a function literal can be used.Essentially, a case sequence is a function literal, only more general. Instead of having a single entry point and list of parameters, a case sequence has multiple entry points, each withtheir own list of parameters. Each case is an entry point tothe function, and the parameters are specified with the pattern. Thebody of each entry point is the right-hand side of the case. (Chapter 15. Case Classes and Pattern Matching)
scala> val isEven = (x: Int) => { if((x % 2) == 0) true else false } isEven: Int => Boolean = $$Lambda$3888/394887728@36f14bca scala> isEven(3) res10: Boolean = false scala> isEven(4) res11: Boolean = true
- もうちょっと短くしてこれでも大丈夫だった。
scala> val isEven = (x: Int) => (x % 2) == 0 isEven: Int => Boolean = $$Lambda$4044/817940743@616ae52
- ケースシーケンス中に関数リテラルを埋め込んでみる。
scala> val isEven: Int => Boolean = { | case x: Int => (x % 2) == 0 | } isEven: Int => Boolean = $$Lambda$4043/1380981831@d5d3ee scala> isEven(10) res49: Boolean = true scala> isEven(11) res50: Boolean = false
- ケースシーケンスを val にひもづかせる時の値としての関数(function values)の書き方は少し特殊だが以下のようだ。PiS3 に説明の記述が見当たらなかった。|ω・)
val variable_name: argument_type => return_type = { ... body ... }