【发布时间】:2016-01-22 23:58:59
【问题描述】:
以下代码无法编译:
import scala.language.implicitConversions
trait Base {
class Wrp[+T](val v: T) // wrapper / internal representation
}
trait BooleanOps extends Base {
// implicit conversion
implicit def lift2BooleanOpsCls(x: Boolean): BooleanOpsCls =
new BooleanOpsCls(new Wrp[Boolean](x))
class BooleanOpsCls(wx: Wrp[Boolean]) {
def ||(wy: =>Wrp[Boolean]): Wrp[Boolean] = new Wrp[Boolean](wx.v || wy.v)
}
}
trait MyExample extends BooleanOps {
// test method
def foo(): Wrp[Boolean] = {
val ret: Wrp[Boolean] = false || new Wrp[Boolean](true)
ret
}
}
输出:
MyExample.scala:18: error: type mismatch;
found : MyExample.this.Wrp[Boolean]
required: Boolean
val ret: Wrp[Boolean] = false || new Wrp[Boolean](true)
^
但如果我:
1) 将 class Wrp 放在 Base 之外
或
2) 将BooleanOps 的主体移动到MyExample
一切都会编译。
为什么原始示例不起作用?如果您对此行为有所了解,我们将不胜感激。谢谢。
【问题讨论】:
标签: scala implicit-conversion implicit traits