我正在学习Scala,并希望让以下代码运行:
trait Gene[+T] {
val gene: Array[T]
}
编译器报错如下:
covariant type T occurs in invariant position in type => Array[T] of value gene
我知道可以采取以下方式:trait Gene[+T] {
def gene[U >: T]: Array[U]
}
但这并没有解决问题,因为我需要一个值:实际上我想说的是“我不关心内部类型,我知道基因将有一个返回其内容的基因字段”。(这里的+T是因为我想做类似于
type Genome = Array[Gene[Any]]
的事情,然后将其用作对单个基因类的包装器,以便我可以拥有异构数组类型)在Scala中是否可能做到这一点,或者我只是采取了错误的方法?使用不同的结构,例如Scala本地协变类,会更好吗?
提前感谢!
P.S.:我也尝试过使用class和abstract class而不是trait,但结果总是相同!
编辑:在Didier Dupont的友好建议下,我得出了这段代码:
package object ga {
class Gene[+T](val gene: Vector[T]){
def apply(idx: Int) = gene(idx)
override def toString() = gene.toString
}
implicit def toGene[T](a: Vector[T]) = new Gene(a)
type Genome = Array[Gene[Any]]
}
package test
import ga._
object Test {
def main(args: Array[String]) {
val g = Vector(1, 3, 4)
val g2 = Vector("a", "b")
val genome1: Genome = Array(g, g2)
println("Genome")
for(gene <- genome1) println(gene.gene)
}
}
现在我认为我可以在不同类型中放置和检索数据,并使用所有类型检查工具!
typed
但是没有使用它。它应该在第二行而不是gene
对吗? - Tomas Lazaro