androidengineers.Book a session
โ† All interview questions
KotlinIntermediate4 min

Covariance in Kotlin?

Answer

Covariance allows you to use a subtype in place of a supertype. In Kotlin generics, it is denoted by the out keyword.

Producer (out)

  • If a generic class only returns (produces) type T, it can be covariant.
  • List<out T> is covariant. A List<String> IS A List<Any>.
val strings: List<String> = listOf("A", "B")
val objects: List<Any> = strings // Valid because List is covariant (out T)

Contravariance (in)

  • If a generic class only consumes type T, it is contravariant.
  • Denoted by in.
  • Comparable<in T>. A Comparable<Any> can compare Strings.

Mark this when you can explain the answer in your own words.

Share & Help Others

Help fellow developers prepare for interviews

Sharing helps the Android community grow ๐Ÿ’š

Keep practising