开发者

Why can't this simple example be compiled?

This a very simple scala sample, but it can't be compiled:

abstract class Box[+A] {
    var value: A = _
}

The error is:

covariant type A occurs in contravariant position in type A of parameter of setter value_=

What I want the class to do is:

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)
    }
}


It does not compile because it is incorrect. If scala were to allow you to do it, then you could violate type safety. For example:

import scala.annotation.unchecked.uncheckedVariance

abstract class Box[+A] {
    var value: A  @uncheckedVariance = _
}

class StringBox extends Box[String]
val sb = new StringBox; sb.value = "abc"
val sa: Box[Any] = sb
sa.value = 5
println(sb.value.length)


Mutable classes (and your class Box is mutable) cannot be covariant in the type of their mutable field. You can make Box immutable though

abstract class Box[+A] { val value: A }


Please see the answer to this question: Scala covariance / contravariance question

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜