0
0
Kotlinprogramming~5 mins

Generic class declaration in Kotlin

Choose your learning style9 modes available
Introduction

Generics let you create classes that work with any type, making your code flexible and reusable.

When you want a class to handle different types without rewriting it.
When storing or processing items of various types in a single class.
When creating collections or containers that can hold any type of data.
When you want to avoid code duplication for similar classes with different types.
Syntax
Kotlin
class ClassName<T> {
    // class body using T
}

The <T> after the class name declares a generic type parameter named T.

You can use T inside the class as a placeholder for any type.

Examples
A simple generic class Box that holds a value of any type T.
Kotlin
class Box<T>(val value: T) {
    fun getValue(): T = value
}
A generic class with two type parameters, A and B, to hold two values of possibly different types.
Kotlin
class Pair<A, B>(val first: A, val second: B)
A generic stack class that can store items of any type T.
Kotlin
class Stack<T> {
    private val items = mutableListOf<T>()
    fun push(item: T) { items.add(item) }
    fun pop(): T? = if (items.isNotEmpty()) items.removeAt(items.size - 1) else null
}
Sample Program

This program creates two Box objects: one holding an integer and one holding a string. It prints their contents.

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

fun main() {
    val intBox = Box(123)
    val stringBox = Box("hello")
    println("Int box contains: ${intBox.getValue()}")
    println("String box contains: ${stringBox.getValue()}")
}
OutputSuccess
Important Notes

You can name the generic type parameter anything, but T is common for "Type".

Generics help catch type errors at compile time, making your code safer.

Summary

Generics let classes work with any type without rewriting code.

Declare generics using angle brackets after the class name, like <T>.

Use generic classes to write flexible and reusable code.