我对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]
。我错过了什么?
答案 0 :(得分:6)
CircleShapeThemes
不一个ShapeThemes[ShapeTheme]
,它是ShapeThemes[CircleShapeTheme]
。
“但是”,您可以反对,“CircleShapeTheme
是ShapeTheme
!确实,但是默认情况下不会传播该子类关系。您必须通过创建类型参数来请求它协变:abstract class ShapeThemes[+T <: ShapeTheme]