[問題] Scala上generic和implicit的怪問題

看板Programming作者 (coolcomm)時間11年前 (2013/01/14 11:49), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串1/2 (看更多)
以下是三段很像的程式碼 // (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)
文章代碼(AID): #1Gyu1Oxp (Programming)
文章代碼(AID): #1Gyu1Oxp (Programming)