Declaration-site variance can be thought of as declaration of use-site variance once and for all the use-sites.
class Consumer<in T> { fun consume(t: T) { ... } }
fun charSequencesConsumer() : Consumer<CharSequence>() = ...
val stringConsumer : Consumer<String> = charSequenceConsumer() // OK since in-projection
val anyConsumer : Consumer<Any> = charSequenceConsumer() // Error, Any cannot be passed
val outConsumer : Consumer<out CharSequence> = ... // Error, T is `in`-parameter
Widespread examples of declaration-site variance are List<out T>
, which is immutable so that T
only appears as the return value type, and Comparator<in T>
, which only receives T
as argument.
Use-site variance is similar to Java wildcards:
Out-projection:
val takeList : MutableList<out SomeType> = ... // Java: List<? extends SomeType>
val takenValue : SomeType = takeList[0] // OK, since upper bound is SomeType
takeList.add(takenValue) // Error, lower bound for generic is not specified
In-projection:
val putList : MutableList<in SomeType> = ... // Java: List<? super SomeType>
val valueToPut : SomeType = ...
putList.add(valueToPut) // OK, since lower bound is SomeType
putList[0] // This expression has type Any, since no upper bound is specified
Star-projection
val starList : MutableList<*> = ... // Java: List<?>
starList[0] // This expression has type Any, since no upper bound is specified
starList.add(someValue) // Error, lower bound for generic is not specified
See also:
Variant Generics interoperability when calling Kotlin from Java.
Parameter | Details |
---|---|
TypeName | Type Name of generic parameter |
UpperBound | Covariant Type |
LowerBound | Contravariant Type |
ClassName | Name of the class |