0
0
Kotlinprogramming~5 mins

Why generics provide type safety in Kotlin

Choose your learning style9 modes available
Introduction

Generics help catch mistakes early by making sure you only use the right types with your code. This keeps your program safe and avoids errors.

When you want to create a list that only holds one type of item, like only numbers or only words.
When writing a function that works with different types but should keep the type consistent.
When you want to avoid mistakes by mixing different types in collections or classes.
When you want your code to be reusable but still safe from type errors.
Syntax
Kotlin
class Box<T>(val value: T) {
    fun getValue(): T {
        return value
    }
}

T is a placeholder for any type you want to use.

You specify the actual type when creating an object, like Box for integers.

Examples
Here, intBox only holds integers and stringBox only holds strings.
Kotlin
val intBox = Box<Int>(123)
val stringBox = Box<String>("hello")
This function can print any type, but keeps the type consistent for each call.
Kotlin
fun <T> printItem(item: T) {
    println(item)
}
Sample Program

This program shows two boxes holding different types safely. Trying to put the wrong type causes an error before running.

Kotlin
class Box<T>(val value: T) {
    fun getValue(): T {
        return value
    }
}

fun main() {
    val intBox = Box<Int>(123)
    val stringBox = Box<String>("hello")

    println(intBox.getValue())
    println(stringBox.getValue())

    // The following line would cause a compile error if uncommented:
    // intBox.value = "wrong type"
}
OutputSuccess
Important Notes

Generics help find errors while writing code, not when running it.

They make your code flexible and safe at the same time.

Summary

Generics keep your code safe by checking types early.

They let you write reusable code that works with many types.

Using generics prevents mixing wrong types and bugs.