What if you could safely use anything without knowing exactly what it is?
Why Star projection for unknown types in Kotlin? - Purpose & Use Cases
Imagine you have a box with many different toys, but you don't know exactly which toys are inside. You want to play safely without breaking anything, but you can't see or guess the exact toy type.
Trying to handle each toy manually means guessing its type or risking errors. You might try to treat a toy as a car when it's actually a doll, causing confusion and mistakes in your code.
Star projection lets you say, "I don't know the exact type, but I want to work safely with whatever is inside." It acts like a safe cover that hides the unknown details but still lets you use the box without errors.
fun printList(list: List<Any>) {
for (item in list) {
println(item)
}
}fun printList(list: List<*>) {
for (item in list) {
println(item)
}
}It enables you to write flexible and safe code that works with any type without knowing the details upfront.
When you receive a list from a library but don't know what type of items it holds, star projection lets you process the list safely without errors or crashes.
Star projection helps handle unknown types safely.
It prevents errors when working with generic types you don't know.
It makes your code more flexible and robust.