Signup/Sign In
LAST UPDATED: AUGUST 10, 2020

Kotlin Generics

In this tutorial we will learn about Kotlin Generics. The concept of Generics allows us to make our classes and functions data type independent.

Let us consider a scenario in which we want to create a class which has some functionality. The functions of this class work for a specific data type: String. Now there is a need for the same function to support the datatype Int also. So what will you do? Create a new function for this, or create a new class altogether. Well! using Generics, you can use the same class, same function and handle any data type, by making the function generic.

Generics allows us to define classes, functions and properties which can be accessed using different data types. The data type of generics declaration is checked at compile-time. So, if there is any error then it will be given at compile time only.

Generic type classes and functions are defined as parameterized type using angle brackets <>.

Kotlin Parameterized class

Let us create a parameterized class which has some functions:

class Rank<T>(var rank: T){
    fun printRank(name: String) {
        println("The rank of $name is $rank")
    }
}

fun main(){
    val rank = Rank<Int>(12)
    rank.printRank("Ninja")
    
    val rankNew = Rank<String>("First")
    rankNew.printRank("New Ninja")
}


The rank of Ninja is 12
The rank of New Ninja is First

In this example, we created a parameterized class Rank. It takes a parameter rank of the same type T as class type. It contains a function which prints the rank. In main() function we created two objects of Rank class. The first object is of Int type and second object is of String class.

In fact, the compiler can also interpret the data type of class using type inference from the data type of constructor parameter passed. So, this code will also work like the code above:

fun main(){
    val rank = Rank(12)
    rank.printRank("Ninja")
    
    val rankNew = Rank("First")
    rankNew.printRank("New Ninja")
}


The rank of Ninja is 12
The rank of New Ninja is First

Kotlin Parameterized function

In the similar manner we can also create generic functions:

fun <T>printMessage(message:T) {
    println("Message is: $message")
}
fun main(){
    printMessage("Hello World!!")
    printMessage(123)
    val map = mapOf("Maths" to 1, "Science" to 2, "English" to 3)
    printMessage(map)
}


Message is: Hello World!!
Message is: 123
Message is: {Maths=1, Science=2, English=3}

In this example we created a printMessage() function which takes generic data type parameters and prints them.

Summary

In this tutorial we learned about basics of generics in Kotlin. In the next tutorial we will learn about Extension functions in Kotlin.



About the author:
I'm a writer at studytonight.com.