Covariant type T occurs in contravariant position

I know that this question was asked before, but either the answers do not apply to this case, or I do not understand them.

Basically, why doesn't the following work (a simple example that recreates my problem)?

class Test[+T] { var list: List[T] = _ } 

The problem I am facing is that I have an object in which I want to pass an instance of Test [Nothing] (an empty test), and this will not work unless I make a test co-option in T.

+18
scala
Jan 29 '13 at 14:07
source share
1 answer

Running test covariant in T means that Test[A] is a subtype of Test[Any] for any A So let's create a Test :

 val test_string = new Test[String] 

Now we have Test[String] , and the contained list is of type List[String] .

Since Test[String] is a subtype of Test[Any] , it should be allowed:

 val test_any : Test[Any] = test_string 

And now we have Test[Any] , so test_any.list is a type of List[Any] , which means the following should be true:

 test_any.list = List[Any]() 

This means that we just assigned a List[Any] list item to test_strings, which should not be allowed, as it is assumed to be List[String] , not List[Any] . It also means that you could add anything at all to the list, since it is a type of List[Any] .

+25
Jan 29 '13 at 14:23
source share



All Articles