Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Difference between "*" and "Any" in Kotlin generics
In any programming language, generics are a powerful feature using which developers can create custom data type to manipulate a program in a different manner. There are many ways in which we can define generics in Kotlin.
In this article, we will demonstrate the difference between "*" and "Any" keywords 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.
Example - usage of "*"
fun main(args: Array) { val num = arrayOf(1, 2, 3, 4) ArrayUtil().findElement(num,2) } class ArrayUtil(){ // passing generic array to a function fun findElement(array:Array,element:Int){ for(i in array.indices){ if(array[i]==element){ println("Element found at " +i) } } } }
Output
It will generate the following output:
Element found at 1
Example – Use of "Any"
fun main(args: Array) { var objet = genericsExample ("JAVA") var objet1 = genericsExample (10) } class genericsExample (input:Any?) { init { println("I am getting called with the value "+input) } }
Output
It will generate the following output
I am getting called with the value JAVA I am getting called with the value 10
Advertisements
