What Are Generics in Kotlin: Simple Explanation and Examples
generics let you write flexible and reusable code by allowing classes and functions to work with any data type. They act like placeholders for types, so you can create one version of code that works with many types safely.How It Works
Generics in Kotlin work like a recipe that can use different ingredients. Instead of writing a new recipe for each ingredient, you write one recipe that can accept any ingredient you want. This means you write code once and use it with many types without repeating yourself.
Imagine a box that can hold any kind of item. Instead of making a new box for each item type, generics let you make one box that can hold anything, but still keeps track of what it holds. This helps avoid mistakes, like putting the wrong item in the box or taking out the wrong type.
Example
This example shows a generic class Box that can hold any type of item. We create boxes for an Int and a String to see how it works.
class Box<T>(val item: T) { fun getItem(): T { return item } } fun main() { val intBox = Box(123) val stringBox = Box("Hello") println(intBox.getItem()) println(stringBox.getItem()) }
When to Use
Use generics when you want to write code that works with different types but follows the same logic. This is common in collections like lists or maps, where you want to store many items but keep track of their type.
For example, if you create a function to swap two values, generics let you write it once and use it for numbers, strings, or any other type. This saves time and reduces errors by avoiding duplicate code.
Key Points
- Generics let you write flexible code that works with any type.
- They help avoid code duplication and type errors.
- Kotlin uses
<T>to declare generic types. - Generics are widely used in collections and utility functions.
Key Takeaways
<T> to declare generic classes or functions in Kotlin.