flâneur — a map of the web's best reading

Generics: in, out, where | Kotlin Documentation

kotlinlang.org · 3,457 words · saved by 1 readers

But if the parameters can be inferred, for example, from the constructor arguments, you can omit the type arguments: One of the trickiest aspects of Java's type system is the wildcard types (see Java Generics FAQ). Kotlin doesn't have these. Instead, Kotlin has declaration-site variance and type projections. Let's think about why Java needs these mysterious wildcards. First, generic types in Java are invariant, meaning that List is not a subtype of List . If List were not invariant, it would have been no better than Java's arrays, as the following code would have compiled but caused an exception at runtime: Java prohibits such things to guarantee runtime safety. But this has implications. For example, consider the addAll() method from the Collection interface. What's the signature of this method? Intuitively, you'd write it this way: But then, you would not be able to do the following (which is perfectly safe): That's why the actual signature of addAll() is the following

Generics: in, out, where Classes in Kotlin can have type parameters, just like in Java: class Box<T>(t: T) { var value = t } To create an instance of such a class, simply provide the type arguments: val box: Box<Int> = Box<Int>(1) If the compiler can infer the type arguments, for example, from the constructor arguments, you don't need to specify them explicitly: val box = Box(1) // 1 has type Int, so the compiler figures out that it is Box<Int> Variance One of the trickiest aspects of Java's type system is the wildcard types (see Java Generics FAQ ). Kotlin doesn't have these. Instead, Kotlin

Explore this link on the map →

related reading