[問題] Scala上generic和implicit的怪問題
以下是三段很像的程式碼
// (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)
討論串 (同標題文章)