【发布时间】:2012-12-31 14:48:36
【问题描述】:
我对这段代码有点困惑:
abstract class Abstract3 {
type TP
protected def action(arg: TP): TP
def *[T <% TP](arg: T) = action(arg)
}
class Concrete3(str: String) extends Abstract3 {
type TP = Concrete3
override protected def action(arg: TP) = new TP("")
}
class Test3 {
implicit def str2Concrete(s: String)(implicit num: Int) = new Concrete3(s)
implicit val a = 1
val foo = "AA" * "BB" * "CC"
}
Scala 编译器不编译,报错:
test.scala:15: error: value * is not a member of String val foo = “AA”*“BB”*“CC” ^ 发现一个错误
但是如果我们把 ''*'' 改成 '/' 或者别的什么,就会编译成功:
abstract class Abstract3 {
type TP
protected def action(arg: TP): TP
def /[T <% TP](arg: T) = action(arg)
}
class Concrete3(str: String) extends Abstract3 {
type TP = Concrete3
override protected def action(arg: TP) = new TP("")
}
class Test3 {
implicit def str2Concrete(s: String)(implicit num: Int) = new Concrete3(s)
implicit val a = 1
val foo = "AA" / "BB" / "CC"
}
顺便说一句,如果我们删除 'implicit num: Int',它也能正常编译。
abstract class Abstract3 {
type TP
protected def action(arg: TP): TP
def *[T <% TP](arg: T) = action(arg)
}
class Concrete3(str: String) extends Abstract3 {
type TP = Concrete3
override protected def action(arg: TP) = new TP("")
}
class Test3 {
implicit def str2Concrete(s: String) = new Concrete3(s)
val foo = "AA" * "BB" * "CC"
}
* 是否具有比隐式参数更高的优先级,但 / 具有更低的优先级?还是有其他原因 * 在这种情况下不起作用?
【问题讨论】:
-
如果 Daniel C. Sobrals 的评论是正确的,您可以考虑将操作符命名为“:*”。看起来不太好,但确实可以。
标签: scala operator-keyword operator-precedence