Scala 中自定义类型的一元运算符定义
Unary operator definitions for custom types in Scala
已尝试 运行 此代码:
def ! : Int => Boolean = (p : Int => Boolean) => !p
有编译错误:
[error] value unary_! is not a member of Int => Boolean
[error] def ! : Int => Boolean = (p : Int => Boolean) => !p
突出显示“!p”的错误
编译器不应该自动计算出 p 的结果是 Boolean
吗?
提前致谢
编辑:根据评论,还尝试了以下方法。已经使用其他方法完成了我的任务,但是,我正在尝试学习如何定义一元运算符
def unary_! : Int => Boolean = (p : Int => Boolean) => !(p(_))
在 "!(p(_))"
处仍然出现编译器错误
也许您打算这样:
scala> class C(p: Int => Boolean) { def unary_! : Int => Boolean = !p(_) }
defined class C
scala> val c = new C(i => i < 0)
c: C = C@4d9cad9d
scala> (!c)(42)
res0: Boolean = true
已尝试 运行 此代码:
def ! : Int => Boolean = (p : Int => Boolean) => !p
有编译错误:
[error] value unary_! is not a member of Int => Boolean
[error] def ! : Int => Boolean = (p : Int => Boolean) => !p
突出显示“!p”的错误
编译器不应该自动计算出 p 的结果是 Boolean
吗?
提前致谢
编辑:根据评论,还尝试了以下方法。已经使用其他方法完成了我的任务,但是,我正在尝试学习如何定义一元运算符
def unary_! : Int => Boolean = (p : Int => Boolean) => !(p(_))
在 "!(p(_))"
也许您打算这样:
scala> class C(p: Int => Boolean) { def unary_! : Int => Boolean = !p(_) }
defined class C
scala> val c = new C(i => i < 0)
c: C = C@4d9cad9d
scala> (!c)(42)
res0: Boolean = true