Re: [問題] Scala上generic和implicit的怪問題
三段程式沒有很像啊
※ 引述《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
01/15 11:21, 1F
→
01/15 11:23, , 2F
01/15 11:23, 2F
→
01/15 11:52, , 3F
01/15 11:52, 3F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):
Programming 近期熱門文章
PTT數位生活區 即時熱門文章