简体   繁体   English

Scala-传递派生类型的类代替超类型的类

[英]Scala - Passing Class of derived type in place of Class of supertype

So, I have the following use case. 因此,我有以下用例。

There is a class called SinglePredictionTester with the following implementaion. 有一个名为SinglePredictionTester的类,具有以下实现。

class SinglePredictorTester[T <: Class[SurvivalPredictor]](predictorClass: T,
                                                            dataSplitter: DataSplitter,
                                                            titanic: DataFrame) extends PredictionTester {

  import titanic.sqlContext.implicits._

  override def test: Map[SurvivalPredictor, Double] = ???

}

The idea is for this class is to take a subclass of SurvivalPredictor class, instantiate it inside and execute some methods to test it's accuracy. 该类的想法是采用SurvivalPredictor类的子类,在内部实例化该类并执行一些方法来测试其准确性。

SurvivalPredictor has many implementations. SurvivalPredictor具有许多实现。

I plan to call the SinglePredictionTester like this: 我打算这样称呼SinglePredictionTester:

  val test: Map[SurvivalPredictor, Double] = new SinglePredictorTester(classOf[SexBasedPredictor],
    new DataSplitter {},
    new DataFrameLoader {}.load(getPathForResource("train.csv"),
      sqlContext)).test

However this doesn't compile and gives me following error: 但是,这不能编译,并给我以下错误:

Error:(13, 46) inferred type arguments [Class[com.dhruvk.kaggle.predictors.implementations.SexBasedPredictor]] do not conform to class SinglePredictorTester's type parameter bounds [T <: Class[com.dhruvk.kaggle.predictors.SurvivalPredictor]]
  val test: Map[SurvivalPredictor, Double] = new SinglePredictorTester(classOf[SexBasedPredictor],
                                             ^

I'm unable to figure out how to get this working. 我不知道如何使它工作。

The problem is that Class is not covariant in its generic type parameter. 问题是Class在其泛型类型参数中不是协变的。 However, you can solve the problem by specifying T <: SurvivalPredictor . 但是,您可以通过指定T <: SurvivalPredictor来解决问题。

class SinglePredictorTester[T <: SurvivalPredictor](
    predictorClass: Class[T],
    dataSplitter: DataSplitter,
    titanic: DataFrame) extends PredictionTester {

  import titanic.sqlContext.implicits._

  override def test: Map[SurvivalPredictor, Double] = ???
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM