0

我在网上搜索但没有得到有用的结果。也许这很愚蠢,但我正在努力让它发挥作用。我的问题的描述可以在以下示例中显示:

trait EnumType
class MyEnum extends EnumType

trait Coherence[S <: EnumType] {
    def printS(s: S): Unit
}

class MyCoherence extends Coherence[EnumType] {
    override def printS(s: EnumType): Unit = println("printS in MyCoherence")
}

case class MyCaseClass(coh: Coherence[_ <: EnumType])

object HelloWorld {
   def main(args: Array[String]) {
       val myCoh = new MyCoherence
       val m = MyCaseClass(myCoh)
       val myEnum = new MyEnum

       myCoh.printS(myEnum)
       m.coh.printS(myEnum) // >>> problematic line 21
      println("Hello, world!")
   }
}

正如你所看到的,我有一个案例类MyCaseClass,它接受一个实例Coherence[_ <: EnumType]作为参数。

这个实例有一个简单printS()的打印一些消息。

在 中main,当我尝试调用printSofm.coh时,编译器给出以下错误:

$scalac *.scala
HelloWorld.scala:21: error: type mismatch;
 found   : myEnum.type (with underlying type MyEnum)
 required: _$1
       m.coh.printS(myEnum)
                    ^
one error found

当我这样做(而不是)时,似乎coh删除了的类型界限。m.coh.printS_$1_$1 <: EnumType

我想知道我是否错过了以printS这种方式使用的东西?谢谢

4

1 回答 1

0

类型绑定没有被删除,只是在这种情况下没有打印。问题是这m.coh可能是Coherence[SomeOtherEnum]

class SomeOtherEnum extends EnumType
class OtherCoherence extends Coherence[SomeOtherEnum] {
    override def printS(s: SomeOtherEnum): Unit = ???
}

val m = MyCaseClass(new OtherCoherence)

因为 thism和你的具有相同的类型,所以m.coh.printS(myEnum)应该在两种情况下都进行类型检查或都不进行类型检查,而且它显然不能在这里工作:它只调用 OtherCoherence.printS()which 接受SomeOtherEnum.

您可以通过强制转换使其编译m.coh

m.coh.asInstanceOf[Coherence[EnumType]].printS(myEnum)

但由于上述原因,它是不安全的:如果m.coh是 a MyCoherence,它将起作用;如果m.coh是一个OtherCoherence,它最终会尝试强制myEnum转换SomeOtherEnum并抛出异常。

于 2020-01-16T17:48:13.263 回答