0
0
Kotlinprogramming~15 mins

Star projection for unknown types in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Star Projection for Unknown Types in Kotlin
📖 Scenario: Imagine you are building a library system that can hold collections of different types of items, like books, magazines, or DVDs. Sometimes, you don't know exactly what type of items a collection holds, but you still want to work with it safely.
🎯 Goal: You will create a Kotlin program that uses star projection to handle collections with unknown types. This helps you work with generic types safely when you don't know the exact type inside.
📋 What You'll Learn
Create a generic class called Box that holds a value of any type.
Create a list of Box objects with different types inside.
Use star projection Box<*> to handle the list with unknown types.
Print the contents of each Box safely using star projection.
💡 Why This Matters
🌍 Real World
Star projection helps when working with libraries or APIs where you don't know the exact generic type but still want to use the data safely.
💼 Career
Understanding star projection is important for Kotlin developers working with generics, especially in Android development and library design.
Progress0 / 4 steps
1
Create the generic class Box
Create a generic class called Box with a property value of type T. This class will hold any type of value.
Kotlin
Need a hint?

Use class Box<out T>(val value: T) to create a generic class with a value property.

2
Create a list of Box objects with different types
Create a list called boxes that contains Box objects holding these exact values: Box(123), Box("Hello"), and Box(45.6).
Kotlin
Need a hint?

Use listOf(Box(123), Box("Hello"), Box(45.6)) to create the list.

3
Use star projection to handle unknown types
Create a variable called unknownBoxes of type List<Box<*>> and assign it the value of boxes. This uses star projection to handle boxes with unknown types.
Kotlin
Need a hint?

Use val unknownBoxes: List<Box<*>> = boxes to declare the variable with star projection.

4
Print the contents of each Box safely
Use a for loop with variable box to iterate over unknownBoxes. Inside the loop, print the value property of each box.
Kotlin
Need a hint?

Use for (box in unknownBoxes) { println(box.value) } to print each value.