編輯後面的兩個答案 我想讓下面的Scala代碼編譯。斯卡拉類型覆蓋
abstract class C {
type T <: C
def x(other: T): (T, T)
}
class C1 extends C {
override type T = C1
override def x(other: C1): (C1, C1) = (this, this)
}
def doSthg(cs1 : List[C]) {
val e1 = cs1(0)
val e2 = cs1(1)
e1.x(e2)
}
但失敗,出現以下消息:
Description Resource Path Location Type
type mismatch; found : e2.type (with underlying type Chromo[G]) required: e1.C PI3.sc /GA/src/org/jts/ga line 76 Scala Problem
type mismatch; found : e2.type (with underlying type org.jts.ga.MI2.C) required: e1.T MI2.sc /GA/src/org/jts/ga line 18 Scala Problem
任何想法?
基本上,我想定義一個像上面C一樣的泛型類,並且在子類(C1)上有正確類型的方法。
直到在soSthg中的C上調用泛型方法爲止都是很好的。
感謝
新的編輯部分
感謝v多少您的答覆。看看下面的代碼,我希望避免asInstanceOf。
abstract class G[T](val t: T) {
def ~(): G[T]
}
abstract class C[T](val g: List[G[T]]) {
def x(other: C[T]): (C[T], C[T])
}
class G1(override val t: Boolean) extends G[Boolean](t){
override def ~() = new G1(!t)
}
class C1(override val g: List[G1]) extends C[Boolean](g) {
override def x(other: C[Boolean]): (C[Boolean], C[Boolean]) = {
val go = other.g.map(e => e.asInstanceOf[G1])
//val go = other.g
val nc1 = new C1(go)
(nc1, nc1) // for demo
}
}
x(other:C [Boolean])的簽名的確是問題。
這會工作:
def doSthg2[T <: C](csl : List[T]) { csl(0).x(csl(1)) }
如何避免asInstanceOf?
的確。像這樣的東西可以工作:def doSthg2 [T <:C](csl:List [T]){csl(0).x(csl(1)) } – jts