Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wildcards generic in Kotlin for variable

Tags:

kotlin

Is it possible to declare generic wildcards in Kotlin like this code in Java:

List<Integer> a = new ArrayList<>();
List<? extends Number> b = a;
like image 868
Khang .NT Avatar asked May 20 '17 16:05

Khang .NT


People also ask

How do you declare a generic variable in Kotlin?

We can make generic variable using this kind of syntax: "val destinationActivity: Class<*>".

What is a generic wildcard?

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.

What is the difference between * and any in Kotlin?

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.


2 Answers

The equivalent in Kotlin would be like this:

val a = ArrayList<Int>()
val b: ArrayList<out Number> = a
like image 120
JK Ly Avatar answered Sep 27 '22 18:09

JK Ly


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
like image 32
Abhishek Aryan Avatar answered Sep 27 '22 18:09

Abhishek Aryan