为什么不能_用于表示方法覆盖中未使用/忽略的参数?

Eri*_*lun 7 scala

考虑:

trait Validation {
  def isValid(str: String): Boolean
}
class AlwaysValid extends Validation {
  override def isValid(_: String) = true
}
Run Code Online (Sandbox Code Playgroud)

产量

<console>:1: error: identifier expected but '_' found.
       override def isValid(_: String) = true
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?或者这只是语言设计师遗漏的东西?


也许这是关于命名参数传递但这只适用于非覆盖,因为覆盖自动"继承"来自重写方法的参数名称,所以这不可能是:

trait Foo {
  def bar(arg0: String): String
}
class Baz extends Foo {
  override def bar(blabla: String) = "hello"
}

new Baz().bar(arg0 = "world")  // works, even though the arg name is blabla in Baz
Run Code Online (Sandbox Code Playgroud)

此外: _允许在lambda中,甚至多次:

scala> val x: Int => Int = _ => 3
x: Int => Int = <function1>

scala> val x: (Int, Int) => Int = (_, _) => 3
x: (Int, Int) => Int = <function2>
Run Code Online (Sandbox Code Playgroud)

vpt*_*ron 6

因为在调用方法时可以使用参数名称.

Scala允许您在覆盖时更改参数的名称(尽管不鼓励),但是如果需要,您总是需要为调用者提供一个名称.