gpt4 book ai didi

Scala 值有不兼容的类型?

转载 作者:行者123 更新时间:2023-12-01 10:42:27 26 4
gpt4 key购买 nike

我对 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com