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<String>) {
   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<String>) {
   var objet = genericsExample<String>("JAVA")
   var objet1 = genericsExample<Int>(10)
}

class genericsExample<Any>(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

Updated on: 23-Nov-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements