为什么val是稳定的标识符而def不是?

Vla*_*nko 5 scala pattern-matching

val模式匹配时可以使用类实例的字段:

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
Run Code Online (Sandbox Code Playgroud)

我想知道为什么def不能类似地使用?

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")
  }
}
Run Code Online (Sandbox Code Playgroud)

我认为,valdef大多是可以互换的.

Jat*_*tin 2

根据参考,您的第二种情况不是有效的模式。val foo之所以有效,是因为它是一个稳定的标识符模式\xc2\xa7 8.1.5,这基本上意味着它检查 if x == a.foo

\n\n

您的第二种情况根本不是任何有效的模式(因为a.bar不是标识符而是声明),因此会出现错误。

\n\n

一种惯用的方法是:

\n\n
def patmat1(a: A, x: Int) {\n  x match {\n    case i if a.bar == x => println("a.foo")\n    case _     => println("not a.foo")\n  }\n} \n
Run Code Online (Sandbox Code Playgroud)\n