の
trait Expr
case class Number(n: Int) extends Expr
case class Sum(e1: Expr, e2: Expr) extends Expr
object CaseExample {
def eval(e: Expr): Int = e match {
case Number(n) => n
case Sum(e1, e2) => eval(e1) + eval(e2)
}
def main(args: Array[String]) {
println(eval(Sum(Number(1), Number(2)))) //> 3
}
}
かなりの構文糖衣が進行中です。case
暗黙的に2つのオブジェクトを作成していることがわかります
object Number extends Expr {
def apply(n: Int) = new Number(n)
}
object Sum extends Expr {
def apply(e1: Expr, e2: Expr) = new Sum(e1, e2)
}
そしてそれが私たちが例えば書くことができる理由でありSum(...)
、クラスを介してオブジェクトをインスタンス化することもSum(...)
できますSum.apply(...)
。
match
コンストラクトもシンタックスシュガーであるというのは正しいですか?もしそうなら、どのように - 例えばcase Number(n)
- コンパイラによって書き換えられますか?
n
incase Number(n)
がどこにも定義されているか、値にバインドされていることがわからないので、私は尋ねています。奇妙なことに、match
構文では最初の文字の大文字と小文字が重要になります (大文字の場合は定数になります)。私が知る限り、これはmatch
関連性のある構造にすぎないため、これは奇妙です.