What is Star Projection in Kotlin: Simple Explanation and Example
star projection is a way to use generic types when you don't know or don't want to specify the exact type argument. It acts like a wildcard, allowing safe access to generic types without full type information.How It Works
Imagine you have a box that can hold any type of fruit, but you don't know which fruit it holds. Star projection in Kotlin is like saying, "I don't know exactly what fruit is inside, but I can still work safely with the box." It lets you use generic types without specifying the exact type parameter.
In Kotlin, when you use a generic class like List<T>, you usually specify the type, like List<String>. But sometimes you want to say, "I want a list of something, but I don't care what." Using star projection with List<*> means you can read items as Any? safely, but you cannot add items because the exact type is unknown.
This helps keep your code safe and flexible when working with generics whose types are not fully known.
Example
This example shows how star projection lets you read from a generic list without knowing its exact type.
fun printList(list: List<*>) {
for (item in list) {
println(item)
}
}
fun main() {
val stringList: List<String> = listOf("apple", "banana", "cherry")
val intList: List<Int> = listOf(1, 2, 3)
printList(stringList)
printList(intList)
}When to Use
Use star projection when you want to work with generic types but don't know or don't want to specify the exact type argument. It is helpful when you only need to read data safely without modifying it.
For example, if you have a function that prints elements of any list regardless of its type, star projection allows you to accept List<*> and safely access its elements as Any?.
This is common in libraries or APIs where the exact generic type is unknown or irrelevant to the operation.
Key Points
- Star projection is Kotlin's way to handle unknown generic types safely.
- It allows reading from generic types but restricts writing to them.
- Use
<*>when you want flexibility without specifying exact types. - It helps avoid unsafe casts and keeps type safety.