Kotlin Declaration-site variance


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.