August 2017
Intermediate to advanced
440 pages
10h
English
Generics in Kotlin are invariant by default. This means that we need to use the type as the type of declared variable or function parameter:
public class Box<T> { } fun sum(list: Box<Number>) { /* ... */ } // Usage sum(Box<Any>()) // Error sum(Box<Number>()) // Ok sum(Box<Int>()) // Error
We can't use a generic type parametrized with Int, which is a subtype of Number, and Any, which is a supertype of Number. We can relax this restriction and change the default variance by using variance modifiers. In Java, there is the question mark (?) notation (wildcard notation) used to represent an unknown type. Using it, we can define two types of wildcard bounds--upper bound and lower bound. In Kotlin, we can achieve similar behavior ...
Read now
Unlock full access