I know this question has been asked before, but either the answers don’t apply to this case, or I don’t understand them.
Basically, why doesn’t the following (simple example that recreates my problem) work ?
class Test[+T] {
var list: List[T] = _
}
The problem I am having is that I have an object, where I want to pass in an instance of Test[Nothing] (the empty Test), and this doesn’t work unless I make Test co-variant in T.
Making test covariant in
Tmeans thatTest[A]is a subtype ofTest[Any]for anyA. So lets create aTest:Now we have a
Test[String]and the containedlistis typeList[String].Since
Test[String]is a subtype ofTest[Any], the following should be allowed:And now, we have a
Test[Any], and thereforetest_any.listis typeList[Any], which means the following should be valid:Which means we just assigned a
List[Any]to test_strings list member, which shouldn’t be allowed, since that is supposed to be aList[String], not aList[Any]. It also means you could prepend anything at all to the list, since it is typeList[Any].