作者coolcomm (coolcomm)
看板Programming
标题[问题] Scala上generic和implicit的怪问题
时间Mon Jan 14 11:49:42 2013
以下是三段很像的程式码
// (1) implicit def中的implicit val
abstract class Abstract1 {
type TP
protected def action[T <% TP](arg: T): TP
}
class Concrete1(s: String) extends Abstract1 {
type TP = Concrete1
override def action[T <% TP](arg: T) = new TP("")
}
class Test1 {
implicit def str2Concrete(s: String)(implicit num: Int) = new Concrete1(s)
implicit val a = 1
//^^^^^^^^^^^^^^^^^^^注意这段
val foo = "AA" action "BB" action "CC"
}
// (2)
abstract class Abstract2 {
type TP
protected def action(arg: TP): TP
def *[T <% TP](a: T) = action(a)
//注意这里
}
class Concrete2(s: String) extends Abstract2 {
type TP = Concrete2
override protected def action(arg: TP) = new TP("")
}
class Test2 {
implicit def str2Concrete(s: String) = new Concrete2(s)
val foo = "AA" * "BB" * "CC"
}
// (3) 1 + 2
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[T <% TP](arg: T) = new TP("")
}
class Test3 {
implicit def str2Concrete(s: String)(implicit num: Int) = new Concrete3(s)
implicit val a = 1
//^^^^^^^^^^^^^^^^^^^和这里
val foo = "AA" * "BB" * "CC"
//错误
}
结果第一段和第二段程式码编译成功 而第三段却编译失败
请问这是为什麽...?
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 36.224.127.140
※ 编辑: coolcomm 来自: 36.224.127.140 (01/14 18:54)