在以下两个答案之后编辑我正在尝试编译以下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调用泛型方法.
谢谢
新编辑部分
非常感谢您的回复.看下面的代码,我希望避免使用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(其他:C [布尔])的签名确实是问题.
这可行:
def doSthg2[T <: C](csl : List[T]) { csl(0).x(csl(1)) }
如何避免asInstanceOf?
C1
编译好.请注意,您可以override
在此处删除关键字:
class C1 extends C { type T = C1 def x(other: C1): (C1, C1) = (this, this) // do you mean (other, this)? }
doSthg
只是无效:你无法证明那e2
是e1.T
.这按预期工作:
def doSthg(e1: C)(e2: e1.T) { e1.x(e2) }
或这个:
abstract class C { ... def create(): T } def doSthg(e1: C) { val e2 = e1.create() e1.x(e2) }
对于您的原始doSthg
方法x
应接受以下任何实例C
:
trait C { def x(other: C): (C, C) }