Search code examples
kotlingenericsvarianceany

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


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.


Solution

  • 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?.