Scala 值有不兼容的类型?

标签 scala types

我对 Scala 还很陌生,打字系统正在摧毁我。我还没有想到一个解决方案或发现一个模式来解决我试图解决的这个特定问题。考虑以下程序:

ShapeType.scala

package models

abstract class ShapeType {
  val themes: ShapeThemes[ShapeTheme] // I think this is where the problem is...?
}

class CircleShapeType extends ShapeType {
  val themes = CircleShapeThemes
}

object CircleShapeType extends CircleShapeType

ShapeThemes.scala

package models

abstract class ShapeThemes[T <: ShapeTheme] {
  val themes: List[T]
}

class CircleShapeThemes extends ShapeThemes[CircleShapeTheme] {
  val themes = List(
    new CircleShapeTheme,
    new CircleShapeTheme,
    new CircleShapeTheme
  )
}

object CircleShapeThemes extends CircleShapeThemes

ShapeTheme.scala

package models

class ShapeTheme

class CircleShapeTheme extends ShapeTheme

当我尝试编译程序(使用 sbt )时,出现以下错误:

[error] /Users/mjs/Projects/sandbox/shape-types/src/main/scala/ShapeType.scala:8: overriding value themes in class ShapeType of type models.ShapeThemes[models.ShapeTheme];
[error]  value themes has incompatible type
[error]   val themes = CircleShapeThemes
[error]       ^
[error] one error found
[error] (compile:compile) Compilation failed
[error] Total time: 2 s, completed Mar 14, 2015 5:08:43 PM

但是,据我所知,CircleShapeThemes 是一个 ShapeThemes[ShapeTheme]。我错过了什么?

最佳答案

CircleShapeThemes 不是 ShapeThemes[ShapeTheme] , 这是一个 ShapeThemes[CircleShapeTheme] .

“但是”,您可能会反对,“一个 CircleShapeTheme 是一个 ShapeTheme!确实,但是默认情况下不会传播子类关系。您必须通过使类型参数协变来请求它: abstract class ShapeThemes[+T <: ShapeTheme]

关于Scala 值有不兼容的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29056440/

相关文章:

scala - 喷雾测试 gzip 解码

java - Scala Singleton 与 Java 的比较

swift - 在 Swift 中创建没有外部属性的结构/协议(protocol)/类

sql - `unknown` 和类型推断的规则是什么?

scala - 如何让 SBT 仅重新运行失败的测试

scala - 如何在 scalaz 中导入身份操作?

types - Rust将闭包附加到向量

haskell - 为什么要为像 'nameless' 这样的 `(->) e` 类型定义一个仿函数实例

haskell - 正确使用类和类型

scala - 如何限制Scala中未处理的 future 数量?