Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 368
Marti Serra Molina Avatar asked Sep 04 '25 16:09

Marti Serra Molina


2 Answers

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<out SomeType> and Invariant<in Nothing>
Covariant<out T : SomeType> Covariant<out SomeType>
Contravariant<in SomeType : T> Lower bound is not supported
like image 53
Yogesh Umesh Vaity Avatar answered Sep 07 '25 16:09

Yogesh Umesh Vaity


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

like image 27
hotkey Avatar answered Sep 07 '25 17:09

hotkey