我正在尝试找出 scala 协变和逆变。可能会混淆两个不同的概念。 处理下面的代码:
sealed trait Algorithm[ +T <: Model, P <: Model, R <: AnyVal] {
def name: String
def train(trainingData: DenseMatrix[Double]): T
def predict(row: DenseVector[R], mlModel : P): R
}
然后我有两种算法类型声明为:
case class LibLinear() extends Algorithm[Active_Linear, Active_Linear, Double] {
override val name = "libLinear"
override def train(trainingData: DenseMatrix[Double]): Active_Linear = {
........
}
override def predict(row: DenseVector[Double], model: Active_Linear): Double = {
..........
}
}
case class SVM() extends Algorithm[Volume_SVM, Volume_SVM, Double] {
override val name = "libSVM"
override def train(trainingData: DenseMatrix[Double]): Volume_SVM = {
..........
}
override def predict(row: DenseVector[Double], model: Volume_SVM): Double = {
...........
}
}
其中Active_Linear
和Volume_SVM
都是Model
的子类型。
现在我不能这样做:
val algorithm: Algorithm[Model, Model, Double] = SVM()
SVM
是Algorithm
的子类型,Volume_SVM
是Model
的子类型。我们用协变
和逆变
符号声明算法
。
最佳答案
这是因为算法仅在涉及 T
时才是协变的。 P
和 R
定义为不变式;您必须根据需要在每个代码前面添加 +
或 -
,然后相应地修改代码。根据您的最终作业,我做了一些假设,这就是我得出的结论:
sealed trait Algorithm[ +T <: Model, +P <: Model, +R <: AnyVal] {
def name: String
def train(trainingData: DenseMatrix[Double]): T
def predict[U >: R, V >: P](row: DenseVector[U], mlModel : V): U
}
case class LibLinear() extends Algorithm[Active_Linear, Active_Linear, Double] {
override val name = "libLinear"
override def train(trainingData: DenseMatrix[Double]): Active_Linear = {
...
}
override def predict[U >: Double, V >: Active_Linear](row: DenseVector[U], model: V): U = {
...
}
}
case class SVM() extends Algorithm[Volume_SVM, Volume_SVM, Double] {
override val name = "libSVM"
override def train(trainingData: DenseMatrix[Double]): Volume_SVM = {
...
}
override def predict[U >: Double, V >: Volume_SVM](row: DenseVector[U], model: V): U = {
...
}
}
你的最后一个作业就可以正常工作了。
关于Scala 协方差分配给父类(super class)型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35201614/