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的结果是一个Boolean吗?

Thanks in advance

编辑:根据评论,也尝试了以下内容。使用其他方法完成了我的任务,然而,我试图学习如何定义一元操作符

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

最新更新