这是一个非常简单的scala示例,但无法编译:
abstract class Box[+A] {
var value: A = _
}错误是:
covariant type A occurs in contravariant position in type A of parameter of setter value_=我想让这个类做的是:
class StringBox extends Box[String]
class DateBox extends Box[Date]
object Testbox {
def main(args: Array[String]) {
val list = ListBuffer[Box[Any]]()
val str = new StringBox
str.value = "abc"
val date = new DateBox
date.value = new Date
list += str
list += date
println(list)
}
}发布于 2011-03-18 19:29:52
可变类(并且您的类Box是可变的)不能在其可变字段的类型中协变。但是,您可以使Box不可变
abstract class Box[+A] { val value: A }https://stackoverflow.com/questions/5351078
复制相似问题