Difference between <out Any?> and <*> in generics in kotlin

Viewed 1032

I don't understand the difference between <out Any?> and <*> in generics. I know that using <*> is like doing <out Any?> and <in Nothing> at the same time, but using <out Any?> cause the same result.

2 Answers

The main difference is that you can't use an out Any? projection on a type parameter that is declared as contravariant (with in at the declaration site) – all of its use sites must be explicitly or implicitly in-projected, too.

Also, for a type parameter with an upper bound T : TUpper, you can't use an out-projection with a type argument that is not a subtype of TUpper. For example, if a type is declared as Foo<T : Number>, a projection Foo<out Any?> is invalid. The out part of the star-projection in the case of Foo<*> means the upper bound, not Any?.

Without Bounds

For the generic type * projection is same as
Invariant<T> Invariant<out Any?> and Invariant<in Nothing>
Covariant<out T> Covariant<out Any?>
Contravariant<in T> Contravariant<in Nothing>

With Bounds

For the generic type * projection is same as
Invariant<T : SomeType> Invariant<SomeType> and Invariant<in Nothing>
Covariant<out T : SomeType> Covariant<out SomeType>
Contravariant<in SomeType : T> Lower bound is not supported
Related