【问题标题】:Scala: method value doesn't conform to type boundsScala:方法值不符合类型界限
【发布时间】:2021-04-23 11:15:22
【问题描述】:

我正在尝试编写一个保存类型变量值的代码。这是示例代码:

class MethodTypeTest
{
    trait TSM[T <: TSM[T]]
    {
        def fit(): FiM[T]
    }

    trait FiM[T <: TSM[_]]
    {
        val fitErrors = mutable.HashMap[String, Double]()
    }

    class TS
    {
        //*** Here I am saving the value of the variable after some computation.
        var bestModel: Option[FiM[_]] = None
    }

    // Now define for SMA
    class SMAM extends FiM[SMA]
    {
        fitErrors("RMSE") = 10
    }
    class SMA extends TSM[SMA]
    {
        override def fit() = new SMAM()
    }
    // Now define for DMA
    class DMAM extends FiM[DMA]
    {
        fitErrors("RMSE") = 10.5
    }
    class DMA extends TSM[DMA]
    {
        override def fit() = new DMAM()
    }

    def main(args: Array[String]): Unit =
    {
        val ts = new TS
        val sma = new SMA
        val dma = new DMA
        val fms: Array[FiM[_]] = Array[FiM[_]](sma.fit(), dma.fit())
        val bestModel: FiM[_] = fms.minBy(m => m.fitErrors("RMSE"))
        // ******** Error in below line ******
        // Error:(48, 24) type arguments [_$3] do not conform to trait FiM's type parameter bounds [T <: MethodTypeTest.this.TSM[_]]
        //        ts.bestModel = Some(bestModel)
        ts.bestModel = Some(bestModel)
    }
}

看起来编译器在抱怨最后一行的类型绑定太开放了。我故意在声明var bestModel: Option[FiM[_]] = None 中保持bestModel 的类型打开,同时定义类TS,因为这个值稍后将计算到FiM 之一。我如何/在哪里可以指定类型绑定以便它工作?

【问题讨论】:

  • 您能否使TS 不可变并作为计算fms.minBy 的结果分配它?即case class TS(bestModel: FiM[_]) 然后val bestModel = TS(bestModel)?
  • 实际的 TS 类还有一堆其他变量被初始化,只有一个 var 需要稍后设置。这就是我不能使用案例类的原因。

标签: scala types


【解决方案1】:

我能够通过在有 FiM[_] 类型注释的任何地方添加类型边界 _ &lt;: TSM[_] 来编译它(使用 Scala 2.13.4 使用 scastie):

class TS {
    var bestModel: Option[FiM[_ <: TSM[_]]] = None
}
//...

val fms: Array[FiM[_ <: TSM[_]]] = Array(sma.fit(), dma.fit())
val bestModel: FiM[_ <: TSM[_]] = fms.minBy(m => m.fitErrors("RMSE"))

我认为这是必要的,因为否则它认为数组的未知 TSM[_] 类型参数必须与 val 的类型参数匹配,因此指定它也应该是通配符可以避免这种情况。

【讨论】:

    猜你喜欢
    • 2019-02-14
    • 2019-06-07
    • 2018-03-19
    • 1970-01-01
    • 2015-06-23
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 2013-05-31
    相关资源
    最近更新 更多