Scala值有不兼容的类型?

mjs*_*sen 3 types scala

我对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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

ShapeTheme.scala

package models

class ShapeTheme

class CircleShapeTheme extends ShapeTheme
Run Code Online (Sandbox Code Playgroud)

当我尝试编译程序(使用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
Run Code Online (Sandbox Code Playgroud)

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

Rex*_*err 6

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

"但是",你可以反对,"a CircleShapeTheme是a ShapeTheme!确实,但是默认情况下不会传播该子类关系.你必须通过使type参数协变来要求它:abstract class ShapeThemes[+T <: ShapeTheme]