Star Projection and When to Use *
Apply star projection for unknown generic types and understand its limits.
What Is Star Projection?
Star projection (*) is Kotlin's way to say "a generic type with an unknown type argument." It's the safe equivalent of Java's raw type or unbounded wildcard <?>.
fun printList(list: List<*>) {
for (item in list) println(item)
}
fun main() {
printList(listOf(1, 2, 3))
printList(listOf("a", "b"))
printList(listOf(true, 42, "mixed"))
}Reading from Star-Projected Types
From a List<*> you can read elements as Any?. You cannot add elements because the actual type is unknown.
fun process(list: List<*>) {
val first: Any? = list.firstOrNull()
println("First: $first, Size: ${list.size}")
// list.add("x") // compile error: can't write to List<*>
}
fun main() {
process(listOf(10, 20, 30))
}All lessons in this course
- Generic Functions and Type Constraints with where
- Declaration-Site Variance: in and out
- Star Projection and When to Use *
- Type Erasure and reified Type Parameters