Kotlin Generics

28. Kotlin Generics 28.1 About Generics 28.2 Parameterized types 28.3 Kotlin Generics In 28.4 Kotlin Generics Out


About Generics

Kotlin generics is a feature of defining class, method, property without specifying terms of type and later we can use for many different types such that they can be operated differently. This is a powerful feature of the kotlin and similar to java programming language, but it introduces two new keywords "in" and "out".

Generics is a type safety feature of kotlin that hold only a single type of object. The generics code is checked at compile time.

Parameterized types

In Kotlin, parameterized types are used in kotlin, which is defined by the angle bracket syntax, like <T>.

Syntax of Generics

class ClassName<T> {

}

In the above syntax, it declares a ClassName of an element T.

We can also declare more than one type parameter.

class ClassName<K, V> {

}

Example

class Agency<T> {

}
class Traveller<X, Y> {

}

We can instantiate the above class with proper type as per our need.

val agn = Agency<String>()
val trav = Traveller<String, Int>()

Example

In this example, we have created a generic class Sales. We have instantiated this class three times with different types of data. The string type is used in obj1, int type in obj2 and float type in obj3.

fun main(args : Array<String>)  { 
    var obj1 = Sales<String>("Hello World")
	var obj2 = Sales<Int>(2000)
	var obj3 = Sales<Float>(0.10f)
}

class Sales<T>(input:T) {
	init {
		println("The input data is "+input)
	}
}
Output
The input data is Hello World
The input data is 2000
The input data is 0.1




Kotlin Generics In

The modifier in is used to apply contravariant type parameter, means to assign generic type as input to its function.

Example

class Company 

open class Employee(val name:String) {
  override fun toString(): String {
    return name
  }
}
class Sales(name:String) : Employee(name) {}

fun main(args : Array<String>)  { 
  val a:Company = Company()   
}

In the above example, in keyword makes the parameter type contravariant.


Kotlin Generics Out

The modifier out is used to apply covariance type parameter, means to assign a generic type as the output of its function.

Example

class Company   

open class Employee(val name:String) {
  override fun toString(): String {
    return name
  }
}
class Sales(name:String) : Employee(name) {}

fun main(args : Array<String>)  { 
  val a:Company = Company() 
}

In the above example, out keyword is used in Company class that makes the parameter covariant. The Company is covariant, Sales is a subtype of Employee.








Read more articles