nus-cs2030 / 2021-s1

27 stars 48 forks source link

AY19/20 Qn3 #568

Closed kennethkks closed 3 years ago

kennethkks commented 3 years ago

Description

Not sure how about the answers that i got after running in jshell. Is this related to Covariance and Contravariance?

Screenshots (if any):

image

coolieKi commented 3 years ago

Yes it is related. A loose rule of thumb would be a producer-like object that produces objects of type T can be of type parameter <? extends T>, while a consumer-like object that consumes objects of type T can be of type parameter <? super T>.

In this case, we can invoke the covariant rule, which says if A2 <: T then Optional <: Optional<? Extends T>, so we can do like Optional<? extends A2>, Optional<? extends A1> etc.

We can also have contravariant rule, which implied that if S <: A2, then Stream <: Stream<? Super S>; thus the possible answers of Optional<? super A2>, etc.

Hope it answers!

kennethkks commented 3 years ago

Ok thanks for the explanation!