Generics

Generics

As in Java, classes in Kotlin may have type parameters:

class Box<T>(t: T) {
    var value = t
}

In general, to create an instance of such a class, we need to provide the type arguments:

val box: Box<Int> = Box<Int>(1)

But if the parameters may be inferred, e.g. from the constructor arguments or by some other means, one is allowed to omit the type arguments:

val box = Box(1) // 1 has type Int, so the compiler figures out that we are talking about Box<Int>

Variance

One of the most tricky parts of Java's type system is wildcard types (see Java Generics FAQ). And Kotlin doesn't have any. Instead, it has two other things: declaration-site variance and type projections.<