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.
Well as per reference, your second case is not a valid pattern. val foo
works because it is a Stable Identifier Pattern § 8.1.5
which basically means that it checks if x == a.foo
.
Your second case is simply not any valid pattern (as a.bar
is not a identifier but a declaration) hence the error.
One idiomatic way would be:
def patmat1(a: A, x: Int) {
x match {
case i if a.bar == x => println("a.foo")
case _ => println("not a.foo")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With