Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why val is stable identifier and def is not?

Fields (vals) 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.

like image 612
Vladimir Parfinenko Avatar asked Nov 01 '22 14:11

Vladimir Parfinenko


1 Answers

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")
  }
} 
like image 136
Jatin Avatar answered Nov 15 '22 06:11

Jatin