Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
813 views
in Technique[技术] by (71.8m points)

scala - covariant type T occurs in contravariant position

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Making test covariant in T means that Test[A] is a subtype of Test[Any] for any A. So lets create a Test:

val test_string = new Test[String]

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

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

val test_any : Test[Any] = test_string

And now, we have a Test[Any], and therefore test_any.list is type List[Any], which means the following should be valid:

test_any.list = List[Any]()

Which means we just assigned a List[Any] to test_strings list member, which shouldn't be allowed, since that is supposed to be a List[String], not a List[Any]. It also means you could prepend anything at all to the list, since it is type List[Any].


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...