Freewind
Freewind

Reputation: 198218

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

Upvotes: 1

Views: 152

Answers (3)

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297165

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)

Upvotes: 4

Matthew Farwell
Matthew Farwell

Reputation: 61705

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

Upvotes: 2

Michael
Michael

Reputation: 10303

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 }

Upvotes: 4

Related Questions