0Pricing
Kotlin Academy · Lesson

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

  1. Generic Functions and Type Constraints with where
  2. Declaration-Site Variance: in and out
  3. Star Projection and When to Use *
  4. Type Erasure and reified Type Parameters
← Back to Kotlin Academy