加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 19:15:55 所属栏目:安全 来源:网络整理
导读:考虑: trait Validation { def isValid(str: String): Boolean}class AlwaysValid extends Validation { override def isValid(_: String) = true} 产量 console:1: error: identifier expected but '_' found. override def isValid(_: String) = true 有
考虑:

trait Validation {
  def isValid(str: String): Boolean
}
class AlwaysValid extends Validation {
  override def isValid(_: String) = true
}

产量

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

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

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

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

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

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

scala> val x: (Int,Int) => Int = (_,_) => 3
x: (Int,Int) => Int = <function2>

解决方法

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读