WEB Button DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

Kotlin - Generics

In this section we talk Data preparing of Kotlin programming language.

generics is pretty similar to Java but Kotlin developer has introduced two new keywords "out" and "in" to make Kotlin codes more readable and easy for the developer. In Kotlin, a class and a type are totally different concepts. As per the example, List is a class in Kotlin, whereas List<String> is a type in Kotlin.
fun main(args: Array<String>) {
   val integer: Int = 1
   val number: Number = integer
   print(number)
}
we have declared one "integer" and later we have assigned that variable to a number variable.Generally, in Kotlin generics is defined by <T> where "T" stands for template, which can be determined dynamically by Kotlin complier.
fun main(args: Array<String>) {
   var objet = genericsExample<String>("JAVA")
   var objet1 = genericsExample<Int>(10)
}
class genericsExample<T>(input:T) {
   init {
      println("I am getting called with the value "+input)
   }
}
We will get the following output in the browser, once we run this code in our coding ground.
I am getting called with the value JAVA
I am getting called with the value 10
In the following example, we will use "out" keyword. Similarly, you can try using "in" keyword.
fun main(args: Array<String>) {
   var objet1 = genericsExample<Int>(10)
   var object2 = genericsExample<Double>(10.00)
   println(objet1)
   println(object2)
}
class genericsExample<out T>(input:T) {
   init {
      println("I am getting called with the value "+input)
   }
}

The above code will yield the following output in the browser.

fun main(args: Array<String>) {
   var objet1 = genericsExample<Int>(10)
   var object2 = genericsExample<Double>(10.00)
   println(objet1)
   println(object2)
}
class genericsExample<out T>(input:T) {
   init {
      println("I am getting called with the value "+input)
   }
}