0
0
KotlinHow-ToBeginner · 3 min read

How to Create Generic Class in Kotlin: Simple Guide

In Kotlin, you create a generic class by adding a type parameter inside angle brackets after the class name, like class Box. This allows the class to work with any data type specified when creating an instance, making your code reusable and type-safe.
📐

Syntax

To define a generic class in Kotlin, use angle brackets <> after the class name with a type parameter, usually a single uppercase letter like T. This type parameter acts as a placeholder for any type you want to use when creating an object of the class.

  • class: keyword to declare a class
  • Box<T>: generic class with type parameter T
  • val value: T: property of type T, meaning it can hold any type specified
kotlin
class Box<T>(val value: T)
💻

Example

This example shows a generic class Box that can hold any type of value. We create two boxes: one for an integer and one for a string. The output prints the stored values.

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

fun main() {
    val intBox = Box(123)
    val strBox = Box("Hello")

    println("Integer box contains: ${intBox.getValue()}")
    println("String box contains: ${strBox.getValue()}")
}
Output
Integer box contains: 123 String box contains: Hello
⚠️

Common Pitfalls

Common mistakes when creating generic classes include:

  • Forgetting to specify the type parameter when creating an instance, which can cause type inference issues.
  • Using raw types without generics, which loses type safety.
  • Trying to use primitive types directly instead of their wrapper types (Kotlin handles this automatically).

Always specify the type or let Kotlin infer it to keep your code safe and clear.

kotlin
/* Wrong: Missing type parameter, raw type usage */
// val box = Box() // Error: Type argument required

/* Correct: Specify type or let Kotlin infer */
val boxInt: Box<Int> = Box(10)
val boxString = Box("text")
📊

Quick Reference

Remember these tips when working with generic classes in Kotlin:

  • Use angle brackets <> to declare type parameters.
  • Type parameters are placeholders for any type you want to use.
  • Specify the type when creating instances or let Kotlin infer it.
  • Generics improve code reuse and type safety.

Key Takeaways

Declare generic classes using angle brackets with a type parameter like T.
Generic classes let you write reusable code that works with any data type.
Always specify or let Kotlin infer the type parameter when creating instances.
Avoid raw types to keep your code type-safe and clear.
Generics help prevent errors by enforcing consistent types at compile time.