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

看板Programming作者 (喲)時間12年前 (2013/01/15 04:12), 編輯推噓1(102)
留言3則, 2人參與, 最新討論串2/2 (看更多)
三段程式沒有很像啊 ※ 引述《coolcomm (coolcomm)》之銘言: : // (3) 1 + 2 : abstract class Abstract3 { : type TP : protected def action(arg: TP): TP : def *[T <% TP](arg: T) = action(arg) //這裡 : } 這裏有一個 method `action` of type (arg: TP): TP 然後 * 不確定是否能夠定義為函數名稱 : class Concrete3(str: String) extends Abstract3 { : type TP = Concrete3 : override protected def action[T <% TP](arg: T) = new TP("") : } 但是這裏跑一個 method `action` 為把 type T 換成 type TP : class Test3 { : implicit def str2Concrete(s: String)(implicit num: Int) = new Concrete3(s) : implicit val a = 1 //^^^^^^^^^^^^^^^^^^^和這裡 : val foo = "AA" * "BB" * "CC" //錯誤 : } : 結果第一段和第二段程式碼編譯成功 而第三段卻編譯失敗 : 請問這是為什麼...? 改寫成以下這樣,似乎OK: abstract class Abstract3 { type TP protected def action(arg: TP): TP def x[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" x "BB" x "CC" } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 36.226.94.177

01/15 11:21, , 1F
囧...我發現我還沒完全了解view bound
01/15 11:21, 1F

01/15 11:23, , 2F
問題還真的是那個* 改成/或&都沒問題XD
01/15 11:23, 2F

01/15 11:52, , 3F
我連val v是什麼東西,理解都有待加強
01/15 11:52, 3F
文章代碼(AID): #1Gz6QoPO (Programming)
文章代碼(AID): #1Gz6QoPO (Programming)