The website uses cookies to optimize your user experience. Using this website grants us the permission to collect certain information essential to the provision of our services to you, but you may change the cookie settings within your browser any time you wish. Learn more
I agree
Summary | 6 Annotations
declaration-site variance and type projections.
2017/09/17 14:39
declaration-site variance
2017/09/17 15:07
we can annotate the type parameter T of Source to make sure that it is only returned (produced) from members of Source<T>, and never consumed. To do this we provide the out modifier:
2017/09/17 15:07
The general rule is: when a type parameter T of a class C is declared out, it may occur only in out-position in the members of C, but in return C<Base> can safely be a supertype of C<Derived>.
2017/09/17 15:09
In addition to out, Kotlin provides a complementary variance annotation: in.
2017/09/17 15:12
. A good example of a contravariant class is Comparable: abstract class Comparable<in T> { abstract fun compareTo(other: T): Int } fun demo(x: Comparable<Number>) { x.compareTo(1.0) // 1.0 has type Double, which is a subtype of Number // Thus, we can assign x to a variable of type Comparable<Double> val y: Comparable<Double> = x // OK!
2017/09/17 15:27