Kotlin

Star Projections (List<*>, etc.)

admin by @admin ADMIN
Jun 13, 2026
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`List<*>` means "list of something I don't need to know exactly" — read-only with Any? as element type. Useful when you genuinely don't care about the parameter.
Kotlin
Raw
fun sizeOf(any: Collection<*>): Int = any.size

fun firstOrNullAny(any: List<*>): Any? = any.firstOrNull()

fun main() {
    // Accepts any list, but treats elements as Any?
    val ints = listOf(1, 2, 3)
    val strs = listOf("a", "b")
    println(sizeOf(ints))                      // 3
    println(sizeOf(strs))                      // 2

    // Use case: a method on Any that wants to enumerate without knowing T
    fun printSample(items: List<*>) {
        println(items.take(3))                  // List<*> → Any? when read
    }
    printSample(ints)
    printSample(strs)

    // Generally prefer a typed parameter — star projection is for when you
    // truly only need read-only access and don't care about the type.
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.