Kotlin — Generics
Generic class
class Box<T>(val value: T)
val intBox = Box(42)
val strBox = Box("Hello")
Generic function
fun <T> singletonList(item: T): List<T> {
return listOf(item)
}
fun <T> List<T>.second(): T {
return this[1]
}
Type constraints
fun <T : Comparable<T>> sort(list: List<T>): List<T> {
return list.sorted()
}
fun <T> printWhenNotEmpty(item: T) where T : CharSequence, T : Comparable<T> {
if (item.isNotEmpty()) println(item)
}
Star projection
fun printList(list: List<*>) {
list.forEach { println(it) }
}
Mini Practice
Write Kotlin code that:
- Creates a generic class
- Writes a generic function
- Uses type constraints
- Demonstrates star projection
Up Next
In the next lesson, you'll learn about DSL — domain-specific languages.
Related Topics
Frequently Asked Questions about Generics
What is Generics in Kotlin?
Generics is a fundamental concept in Kotlin. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Generics?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Generics.
Why is Generics important in Kotlin?
Generics is essential for Kotlin development. Understanding this concept will help you write better code and solve real-world problems more effectively.