0
0
Kotlinprogramming~3 mins

Why Star projection for unknown types in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could safely use anything without knowing exactly what it is?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
fun printList(list: List<Any>) {
    for (item in list) {
        println(item)
    }
}
After
fun printList(list: List<*>) {
    for (item in list) {
        println(item)
    }
}
What It Enables

It enables you to write flexible and safe code that works with any type without knowing the details upfront.

Real Life Example

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.

Key Takeaways

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.