scala - 具有类型成员的案例类的类型推断问题
问题描述
考虑以下示例:
sealed trait Kind
case object B extends Kind
case object C extends Kind
sealed trait Test {
type K <: Kind
val kind: K
}
object Test {
type Aux[KK <: Kind] = Test { type K = KK }
}
sealed trait Suite{
type K <: Kind
val kind: K
val tests: List[Test.Aux[K]]
}
def runSuite(suite: Suite): Unit = {
suite.kind match {
case _: B.type =>
val tests: List[Test.Aux[B.type]] = suite.tests
//
case _: C.type =>
val tests: List[Test.Aux[C.type]] = suite.tests
//
}
}
它看起来很自然,但无法编译:
Error:(47, 51) type mismatch;
found : List[Test.Aux[suite.K]]
(which expands to) List[Test{type K = suite.K}]
required: List[Test.Aux[B.type]]
(which expands to) List[Test{type K = B.type}]
val tests: List[Test.Aux[B.type]] = suite.tests
Error:(50, 51) type mismatch;
found : List[Test.Aux[suite.K]]
(which expands to) List[Test{type K = suite.K}]
required: List[Test.Aux[C.type]]
(which expands to) List[Test{type K = C.type}]
val tests: List[Test.Aux[C.type]] = suite.tests
我用asInstanceOf
解决方法替换了它:
def runSuite(suite: Suite): Unit = {
suite.kind match {
case _: B.type =>
val tests: List[Test.Aux[B.type]] = suite.tests.asInstanceOf[List[Test.Aux[B.type]]]
//
case _: C.type =>
val tests: List[Test.Aux[C.type]] = suite.tests.asInstanceOf[List[Test.Aux[C.type]]]
//
}
}
它编译得很好。这里是asInstanceOf
安全的,这只是Scala 2
类型成员语义的另一个问题,还是背后有另一个原因?
解决方案
推荐阅读
- spring - 订购多个 RouterFunction
- database - BCP 带有逗号分隔符的文件
- python - 如何在python中搜索选择和编辑文本文件的特定部分
- sql - 使用oracle sql的当年出生日期
- performance-testing - Gatling 活跃用户降至零以延长运行时间
- c# - 无法将日期转换为特定格式
- sql-server - 在 SQL Server 中加入 3 个表并添加带有各自数据的新列
- python - 如何在 Linux 上使用 PyQt 方法 QWindow.fromWinId(id)?
- javascript - 正则表达式获取匹配的 iTH 实例
- java - 如何从 html 文件向控制器发送对象或数据?