Everything About Kotlin Generics

Kailash Vaviya Feb 15, 2024
  1. Kotlin Generics
  2. The Problem With Not Using Kotlin Generics
  3. How Kotlin Generics Solve the Problem
  4. Pass a Type of Generic Method in Kotlin
Everything About Kotlin Generics

This article introduces the concept of Kotlin generics. Kotlin generics are powerful features that allow defining classes and functions accessible through various data types.

Kotlin Generics

We need to declare the generics as parameterized types. These parameterized types are an instance of generic types and are declared using angle brackets <>.

The generic classes’ and methods’ type differences are checked at compile time.

Here’s the syntax:

Generic Classes:

class_or_interface<Type>

Genric Methods:

<Type>methodName(parameter: classType<Type>)

We know that Kotlin generics are powerful features, but what makes them powerful? It’s the advantages they offer.

Advantages of Kotlin Generics

Kotlin generics provide the following key benefits.

  1. Type safety - Generic allows holding only a single type of object, eliminating the chances of type errors.
  2. No need for typecasting - Generic mitigates the need for typecasting the object.
  3. Compile-time checks - Checks are done at compile time to avoid runtime errors.

The Problem With Not Using Kotlin Generics

The problem is that without using Kotlin generics, we cannot pass different data types for a parameter. Let’s consider an example to see this.

We will create a Student class with a single parameter. We will then pass two data types: Int and String, to see what happens at the compile time.

class Student (id:Int){
    var id: Int = id
    init {
        this.id = id
        println(id)
    }
}

fun main(args: Array<String>){
    var idInt: Student = Student(17)
    var idString: Student = Student("19") // This throws an error
}

Output:

Passing different data types without using Kotlin generics

As we can see in the output, the program throws a compile-time error. The code accepts the Int type as it is initialized but rejects the String type "19".

How Kotlin Generics Solve the Problem

To overcome the problem with multiple data types, we can use a generic class. We can overcome the issue since the generic class accepts multiple data types for a single parameter.

Here, we will create a generic class that will accept both Int and String types.

class Student<T>(id: T){
    var id: T = id
    init {
        this.id = id
        println(id)
    }
}

fun main(args: Array<String>){
    var idInt: Student<Int> = Student(17)
    var idString: Student<String> = Student("19") // This won't throw an error
}

Output:

Passing different data types using Kotlin generics

In the above example, the objects’ data type changes based on the parameter we pass.

Pass a Type of Generic Method in Kotlin

We have seen how to use Kotlin generics to pass different data types during initialization. But what if we want to pass a generic method as a parameter?

Here’s an example where we create a generic method and pass it as a parameter.

import kotlin.reflect.KClass

data class Person(val city: String)
data class Employee(val city: String)

fun getPerson(): List<Person> = listOf(Person("New York"))
fun getEmployee(): List<Employee> = listOf(Employee("Chicago"))

fun <T: Any> getInfo(xyz: KClass<T>): List<T>? {
    return when(xyz) {
        Person::class -> getPerson() as List<T>
        Employee::class -> getEmployee()  as List<T>
        else -> null
    }
}

fun main(args: Array<String>) {
    val v = listOf(Person::class, Employee::class)
    v.forEach { type ->
        val i = getInfo(type)
        println(i)
    }
}

Output:

Passing a Kotlin generic method as parameter

Kailash Vaviya avatar Kailash Vaviya avatar

Kailash Vaviya is a freelance writer who started writing in 2019 and has never stopped since then as he fell in love with it. He has a soft corner for technology and likes to read, learn, and write about it. His content is focused on providing information to help build a brand presence and gain engagement.

LinkedIn