Fields (val
s) of class instances could be used while pattern matching:
class A {
val foo = 37
def bar = 42
}
def patmat1(a: A, x: Int) {
x match {
case a.foo => println("a.foo")
case _ => println("not a.foo")
}
}
patmat1(new A, 37) // => a.foo
patmat1(new A, 42) // => not a.foo
And I wonder why def
cannot be used analogously?
def patmat2(a: A, x: Int) {
x match {
case a.bar => println("a.bar")
// ^ error: stable identifier required, but a.bar found.
case _ => println("not a.bar")
}
}
I thought that val
and def
are mostly interchangeable.