Star Projection and When to Use *
Apply star projection for unknown generic types and understand its limits.
Star Projection and When to Use * is a free Kotlin Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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))
}Star vs out Any
List<*> and List<out Any?> are equivalent. Star projection is shorthand for the covariant projection with the upper bound.
fun sumStars(list: List<*>): Int = list.size
fun sumOut(list: List<out Any?>): Int = list.size
fun main() {
val l = listOf(1, "two", true)
println(sumStars(l)) // 3
println(sumOut(l)) // 3
}Star in Function Parameters
Use * in function signatures when you need to accept any generic variant but only call methods that don't require knowing T.
fun containerInfo(map: Map<*, *>): String {
return "keys=${map.keys.size}, values=${map.values.size}"
}
fun main() {
val m = mapOf(1 to "one", 2 to "two")
println(containerInfo(m))
}Star with MutableList
For MutableList<*>, you can read as Any? but cannot write at all — the compiler prevents it.
fun clearFirstElement(list: MutableList<*>) {
if (list.isNotEmpty()) {
list.removeAt(0) // OK: remove by index doesn't need T
// list.add("x") // Error: can't write unknown type
}
}
fun main() {
val m = mutableListOf(1, 2, 3)
clearFirstElement(m)
println(m) // [2, 3]
}Class with Star Projection
When checking a generic class type at runtime, use star projection because type arguments are erased.
fun isListOfSomething(obj: Any): Boolean {
return obj is List<*> // OK with star
// obj is List<String> // Warning: cannot check erased type
}
fun main() {
println(isListOfSomething(listOf(1, 2))) // true
println(isListOfSomething("not a list")) // false
}Multiple Star Parameters
A function can have multiple star-projected parameters when working with pairs or maps of unknown types.
fun describeMap(map: Map<*, *>) {
map.forEach { (k, v) ->
println("${k?.javaClass?.simpleName} -> ${v?.javaClass?.simpleName}")
}
}
fun main() {
describeMap(mapOf("key" to 42, 1 to true))
}When NOT to Use Star
Avoid star projection when you need to write to a collection or when you can use a bounded type parameter instead — bounded gives you more information.
// Bad: loses type information
fun addToStar(list: MutableList<*>, item: Any?) {
// list.add(item) // compile error
}
// Better: use bounded type parameter
fun <T : Any> addTyped(list: MutableList<T>, item: T) {
list.add(item)
}
fun main() {
val l = mutableListOf("a")
addTyped(l, "b")
println(l)
}Star with Type Checks and Casts
Use star projection to perform instanceof checks on generic classes, then cast to a specific type for actual work.
fun handleResponse(response: Any) {
if (response is List<*>) {
val list = response as List<*>
println("List with ${list.size} elements")
val first = list.firstOrNull()
if (first is String) println("First string: $first")
}
}
fun main() {
handleResponse(listOf("hello", "world"))
handleResponse(42)
}Practical: Generic Event Dispatcher
A dispatcher that accepts any Handler<*> but dispatches typed events safely.
interface Handler<in T> { fun handle(event: T) }
class LogHandler : Handler<Any> {
override fun handle(event: Any) = println("Event: $event")
}
fun dispatch(handler: Handler<*>, event: Any) {
@Suppress("UNCHECKED_CAST")
(handler as Handler<Any>).handle(event)
}
fun main() {
dispatch(LogHandler(), "click")
dispatch(LogHandler(), 42)
}Star in Reified Contexts
Star projection is especially common in reflection and serialization code where the runtime type is inspected via KClass<*>.
fun printClassName(klass: kotlin.reflect.KClass<*>) {
println(klass.simpleName)
}
fun main() {
printClassName(String::class) // String
printClassName(List::class) // List
printClassName(Int::class) // Int
}Quick Check
What type do you get when reading from a List<*>?
Recap
Star projection (*) accepts any generic variant for read-only access. Use it for type checks, generic utilities, and reflection. Avoid it when you need to write to a collection or when a bounded type parameter gives better type safety.
Frequently asked questions
Is the “Star Projection and When to Use *” lesson free?
Yes — the full text of “Star Projection and When to Use *” is free to read here on the web, and the Kotlin Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Kotlin Academy course, upgrade to CoddyKit PRO.
What will I learn in “Star Projection and When to Use *”?
Apply star projection for unknown generic types and understand its limits. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Kotlin Academy?
No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Star Projection and When to Use *” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Kotlin Academy lesson?
Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Generic Functions and Type Constraints with where
- Declaration-Site Variance: in and out
- Star Projection and When to Use *
- Type Erasure and reified Type Parameters