下面的代碼不會(在斯卡拉2.11)編譯:我怎樣才能別名協泛型類型參數
case class CovariantClass[+R](value: R) {
type T = R
def get: R = value
}
object Main {
def main(args: Array[String]): Unit ={
println(CovariantClass[String]("hello").get)
}
}
的錯誤信息是:
Error:(4, 8) covariant type R occurs in invariant position in type R of type T
type T = R
^
爲什麼我不能別名協變類型參數?如果我刪除行type T = R
,代碼編譯並打印hello
,所以別名似乎是問題。不幸的是,這意味着我不能爲更復雜的類型創建別名,例如type T = List[R]
也不能編譯,儘管List
是協變的。
謝謝你的答案和引用scala規範。我同意重命名'R'而不是別名,但我喜歡爲''[ReturnValueInCaseOfFailure,R]''做一個別名。不幸的是,你提出的解決方法使'T'參數化,但它可能是我能達到我想要的最接近的。 – 2014-10-18 11:18:20