https://kotlinlang.org logo
Title
a

Andreas Sinz

05/14/2018, 8:51 PM
@kiptoo your
Box<T>
is invariant, that means
Box<Int>
is not a subtype of
Box<Number>
https://proandroiddev.com/understanding-generics-and-variance-in-kotlin-714c14564c47
k

kiptoo

05/15/2018, 7:16 AM
hi @Andreas Sinz i now get the general concept (i actually went thru the article you shared earlier, it's excellent). i can tell the compiler that my intention is for IntBox to be a subtype of Box<T> by doing:
open class Box<out T>(t: T) {}
, but what if some of my functions in Box need to take in parameters of type (or subtype) T, e.g
Box.createBox(box: Box<T>)
?
a

Andreas Sinz

05/15/2018, 11:58 AM
@kiptoo you can only have Contravariance or Covariance, meaning
T
only occurs in the in-position or out-position, not both at the same time, otherwise you could create code that fails at runtime
k

kiptoo

05/15/2018, 2:25 PM
good point. looks like i'll have to settle for covariance in this case
thanks!