Is it possible to declare generic wildcards in Kotlin like this code in Java:
List<Integer> a = new ArrayList<>();
List<? extends Number> b = a;
We can make generic variable using this kind of syntax: "val destinationActivity: Class<*>".
The question mark (?) is known as the wildcard in generic programming. It represents an unknown type. The wildcard can be used in a variety of situations such as the type of a parameter, field, or local variable; sometimes as a return type.
When we define a collection with "*", it should contain the object of only that type. There should not be any mix and match between the data types inside a collection. If we use "Any", we can mix and match the data types, which means we can have multiple data types in a collection.
The equivalent in Kotlin would be like this:
val a = ArrayList<Int>()
val b: ArrayList<out Number> = a
Kotlin doesn't have wildcards, it uses the concepts of declaration-site variance and type projections instead.
Please check the documentation, covers pretty extensively.
Kotlin provides so called star-projection
val a = ArrayList<Int>()
val b: ArrayList<out Number> = a
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With