

As a drawback, we aren't as flexible in regards to subtyping of collections at first. It won’t even compile. As a result, it is not possible to run into unexpected runtime errors which makes generic collections safer than covariant arrays ( Effective Java). This means you can’t substitute a List with a List. List, Map, Queue, Set, etc.). Unlike arrays, generic collections are invariant in their parameterized type by default. In Java, an overriding method needs to be covariant in its return type, i.e., the return types of the overridden and the overriding method must be in line with the direction of the inheritance tree of the involved classes. A method treat(): Animal of class AnimalDoctor can be overridden with treat(): Cat in class CatDoctor, which extends AnimalDoctor. Another example of covariance would be type conversion, shown here: public class Animal Īrr = new Object() //throws: : Īs of Java 1.5, generics can be used to inform the compiler which elements are supposed to be stored in a particular collections instance (i.e. The word variance, often referred to in mathematics as well, is used to describe how sub-typing in complex aspects like method return types, type declarations, generic types or arrays relates to the direction of inheritance of the involved classes. There are three terms we need to take into account: Covariance, Contravariance, and Invariance. In Java, we can either use the extends keyword to change/expand behavior of an existing class (inheritance) or use implements to provide implementations for an interface.Īccording to Liskov’s substitution principle, every instance of a class A can be substituted by instances of its subtype B. Many programming languages support the concept of sub-typing, which allows implementing hierarchies that represent relationships like "A cat IS-an animal". Kotlin Generics differ from Java's in how users can define how they behave in sub-typing relationships.Īs opposed to Java, Kotlin allows defining variance on declaration-site, whereas Java only knows use-site variance.

This article covers the concepts of Generics and Variance in Kotlin and compares it to Java.
