Skip to Content

Generics trong Kotlin

🎯 Mục tiêu: Hiểu Generics - viết code type-safe và reusable với type parameters.


💡 Khái niệm

Generics cho phép viết code hoạt động với nhiều types khác nhau một cách type-safe.

class Box<T>(val value: T) fun main() { val intBox = Box(42) // Box<Int> val strBox = Box("Hello") // Box<String> }

📝 Generic Class

class Stack<T> { private val items = mutableListOf<T>() fun push(item: T) = items.add(item) fun pop(): T? = items.removeLastOrNull() fun peek(): T? = items.lastOrNull() val isEmpty: Boolean get() = items.isEmpty() } fun main() { val stack = Stack<Int>() stack.push(1) stack.push(2) println(stack.pop()) // 2 }

🔧 Generic Function

fun <T> singletonList(item: T): List<T> = listOf(item) fun <T, R> List<T>.mapCustom(transform: (T) -> R): List<R> { val result = mutableListOf<R>() for (item in this) { result.add(transform(item)) } return result }

🎯 Constraints với where

fun <T : Comparable<T>> max(a: T, b: T): T { return if (a > b) a else b } // Multiple constraints fun <T> process(item: T) where T : Comparable<T>, T : Cloneable { // ... }

📊 Variance: inout

// out = Producer (covariant) - chỉ đọc interface Producer<out T> { fun produce(): T } // in = Consumer (contravariant) - chỉ ghi interface Consumer<in T> { fun consume(item: T) } // Ví dụ val stringProducer: Producer<String> = object : Producer<String> { override fun produce() = "Hello" } val anyProducer: Producer<Any> = stringProducer // OK vì out

✅ Checklist

  • Tạo generic class và function
  • Sử dụng type constraints
  • Hiểu out (covariant) và in (contravariant)

Tiếp theo: Exception Handling

Last updated on