Generics: in, out, where | Kotlin Documentation
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
- Variance - Rust Compiler Development Guiderustc-dev-guide.rust-lang.org
- TypeScript: Documentation - Genericstypescriptlang.org
- 21. Variance - CS2030S Programming Methodology IInus-cs2030s.github.io
- Higher-order functions and lambdas | Kotlin Documentationkotlinlang.org
- A half-hour to learn Rustfasterthanli.me
- A Guide to @Throws in Kotlin | Baeldung on Kotlinbaeldung.com
- Generic Data Types - The Rust Programming Languagedoc.rust-lang.org
- Exception and error handling | Kotlin Documentationkotlinlang.org
- Validating References with Lifetimes - The Rust Programming Languagedoc.rust-lang.org
- Scala (programming language) - Wikipediaen.wikipedia.org
- 2. Variable and Type - CS2030S Programming Methodology IInus-cs2030s.github.io
- 20. Casting - CS2030S Programming Methodology IInus-cs2030s.github.io