CodeGym /Courses /Kotlin SELF /Star-projection *: List<*>

Star-projection *: List<*>

Kotlin SELF
Level 36, Lesson 3
Available

1. Getting acquainted with List<*>

Imagine real life (and a real project): you’re writing a logging function or a debug printer. It doesn’t matter to it what the list contains — Expense, String, or Int. What matters is iterating over the elements and printing them. Or, for example, showing the size, the first few elements, and then politely staying quiet so you don’t spam the console.

If you try to make a “universal” function via List<Any?>, you’ll quickly run into the fact that yes, List is covariant, but as soon as you want to support mutable collections (MutableList) or containers with more complex type parameters, unpleasant limitations start to show up. That’s why Kotlin provides a separate syntax: List<*>, which reads as:

“This is a list of elements of some type, but which type exactly is unknown.”

And this “unknown” is not philosophy, but concrete compiler rules: what you can do with such a list, and what you cannot.

2. What you can do with List<*>

If we have List<*>, we can do anything “read-only”: size, isEmpty(), iterate with for, access elements by index. But there’s a price: the element type becomes maximally safe — Any?.

Mini example: “print everything”:

fun printAll(xs: List<*>) {
    for (x in xs) {
        println(x) // x: Any?
    }
}

fun main() {
    printAll(listOf(1, 2, 3))
    // 1
    // 2
    // 3

    printAll(listOf("a", "b"))
    // a
    // b
}

Why Any? and not Any? Because Kotlin allows lists whose elements can be null (for example, List<String?>). When the type is unknown, the compiler must keep that possibility in mind as well.

Now an important practical thought: if you take an element out of List<*>, then from that point on you work with it as Any?. Want to call string methods — do a type check first.

fun printStringLengths(xs: List<*>) {
    for (x in xs) {
        if (x is String) {
            println("${x} -> len=${x.length}") // smart-cast to String
        }
    }
}

fun main() {
    printStringLengths(listOf("Kotlin", "is", "fun"))
    // Kotlin -> len=6
    // is -> len=2
    // fun -> len=3
}

Here Kotlin behaves very nicely: after if (x is String) it does a smart cast, and x.length becomes legal.

3. Why you can’t add to MutableList<*>

With List<*> everything looks almost like a “universal list for reading.” And here beginners often make the following logical leap:

“Okay, if List<*> is a list of unknown elements, then MutableList<*> is a mutable list of unknown elements. So I can add something to it… at least null…”

And this is where Kotlin switches into “strict club bouncer” mode: you can’t add.

fun tryToAdd(xs: MutableList<*>) {
    // xs.add(1)    // Compilation error
    // xs.add("hi") // Compilation error
    // xs.add(null) // Also a compilation error
    println(xs.size)
}

Why so strict? Because the real list could be, for example, MutableList<String>. If the compiler let you add an Int, you’d break the contract of a list of strings. And if it let you add null, you’d break MutableList<String> (where null is forbidden).

At the level of Kotlin’s formal model, star-projection is described like this: if the type parameter is unknown, then reading becomes “like out ...”, and writing becomes “like in Nothing” (that is, “nothing can be safely written”). This is spelled out directly in the star-projection rules: for an invariant parameter Foo<T>, the asterisk behaves like safe reading of the upper bound and like a write ban via Nothing.

Intuitively, you can remember it like this: MutableList<*> is a “box labeled: UNKNOWN CONTENTS”. If you start putting items into it, you risk ending up with a “box for spoons” that suddenly contains a screwdriver. The box will survive, but your type contract will not.

Comparison: * is not “Any”

A very common confusion: “the asterisk is Any.” No. Sometimes the read behavior looks similar, but the meaning is different.

Let’s lock in the difference with a small table (and we’ll use simple wording, without diving into formal type theory):

Type What it promises to the caller What you can read What you can add
List<*>
“it’s a list, but the element type is unknown”
Any?
(not applicable,
List
is read-only)
List<Any?>
“it’s a list whose elements are definitely Any?”
Any?
(not applicable)
MutableList<*>
“it’s a mutable list, but the element type is unknown”
Any?
nothing (forbidden by the compiler)
MutableList<Any?>
“it’s a mutable list that stores Any?”
Any?
you can add Any? (including null)

So MutableList<Any?> is a “container for anything.” And MutableList<*> is a “container for who-knows-what,” and that is exactly why writing is prohibited.

Let’s verify with a short example why MutableList<*> is convenient as an input parameter when you’re not going to write:

fun printFirst(xs: MutableList<*>) {
    val first = xs[0]
    println("first=$first") // first: Any?
}

fun main() {
    val names: MutableList<String> = mutableListOf("Ann", "Bob")
    val nums: MutableList<Int> = mutableListOf(10, 20)

    printFirst(names) // first=Ann
    printFirst(nums)  // first=10
}

Here MutableList<*> is useful: the function can accept any MutableList<T>, but it itself promises “I only read.” And the compiler guarantees that you won’t accidentally start adding the “wrong” thing.

What would break without the ban on add

Let’s imagine for a second that Kotlin allowed this:

fun breakWorld(xs: MutableList<*>) {
    xs.add(123) // suppose this were allowed (in reality it isn’t)
}

Now call it:

val names: MutableList<String> = mutableListOf("Ann", "Bob")
breakWorld(names)
println(names[2].length) // what happens here?

If add(123) were allowed, then names would no longer be a “list of strings” in practice. And later you’d get either a runtime crash (for example, a ClassCastException somewhere far away) or, even worse, a silent logic bug.

That’s why Kotlin prefers “better not compile than break for the user.” And MutableList<*> means exactly: “the type is unknown; we have no right to write.”

4. Practice: debug-printing a list in an Expense Tracker

So this doesn’t remain pure theory, let’s plug the idea of List<*> into our console Expense Tracker (the one where we store expenses and show reports). From time to time we want to quickly see “what’s currently in the collection” without writing ten different functions.

Let’s make a small “print list” utility (a plain function, no extensions):

data class Expense(val title: String, val amount: Double)

fun printList(label: String, xs: List<*>) {
    println("== $label (size=${xs.size}) ==")
    for (x in xs) println(x)
}

fun main() {
    val expenses = listOf(
        Expense("Coffee", 3.5),
        Expense("Book", 12.0)
    )
    val tags = listOf("food", "education")

    printList("Expenses", expenses)
    // == Expenses (size=2) ==
    // Expense(title=Coffee, amount=3.5)
    // Expense(title=Book, amount=12.0)

    printList("Tags", tags)
    // == Tags (size=2) ==
    // food
    // education
}

Notice an important effect: printList can’t “know” anything about the element type, and that’s fine. It doesn’t claim to be business logic; it’s a printing utility. In such places, List<*> is a perfect fit.

Preview: print the first N elements

Now let’s add a bit more value: print the first N elements so a huge list doesn’t “kill” the console.

fun printPreview(label: String, xs: List<*>, limit: Int) {
    val n = if (xs.size < limit) xs.size else limit
    println("== $label (showing $n of ${xs.size}) ==")
    for (i in 0 until n) println(xs[i])
}

fun main() {
    val nums = listOf(1, 2, 3, 4, 5)
    printPreview("Numbers", nums, limit = 3)
    // == Numbers (showing 3 of 5) ==
    // 1
    // 2
    // 3
}

Notice how naturally this reads: we don’t know the element type — and we don’t need to, because the “debug print” task requires no operations other than printing.

5. Checking is List<*> and inspecting elements

In real code you sometimes get an Any (for example, from a very generic API, from a JSON tree, from Map<String, Any?>, from an external library). And you want to understand: is this a list or not?

Kotlin allows a check like x is List<*>. This is an important point: the check “this is a list of unknown elements” is allowed, and Kotlin explicitly gives such an example, noting that the elements then have type Any?.

Let’s make a mini function:

fun describeValue(x: Any?) {
    if (x is List<*>) {
        println("This is a list, size=${x.size}") // ok
    } else {
        println("This is not a list")
    }
}

fun main() {
    describeValue(listOf(1, 2, 3)) // This is a list, size=3
    describeValue("hello")         // This is not a list
}

And now the typical next step: “if it’s a list, let’s try to extract strings from it.” Here it’s important to remember that the elements are Any?, so you’ll have to filter via type checks.

fun printOnlyStrings(x: Any?) {
    if (x !is List<*>) return

    for (item in x) {
        if (item is String) {
            println(item.uppercase())
        }
    }
}

fun main() {
    printOnlyStrings(listOf("a", 1, "b", null))
    // A
    // B
}

This looks a bit more verbose than “magical casting,” but it behaves predictably and doesn’t turn your code into a minefield.

6. out/in projections and *

It’s very useful to keep in mind the difference between “I know what the elements are, but I want to restrict operations” and “I don’t know what the elements are at all.”

In MutableList<out Number> you know it’s a “list of some numbers,” so you can safely read as Number, but you can’t add (because which numbers exactly is unknown). In MutableList<in Int> you know it’s safe to add Int, but you’ll only be able to read in the most general way (usually as Any?).

And MutableList<*> is “I know nothing”: neither an upper bound beyond Any?, nor a lower bound for writing. So it is maximally strict about writes.

You can picture it as an “information slider”:

flowchart LR
    A["MutableList⟨Any?⟩
(I know everything: can read Any? and write Any?)"] --> B["MutableList⟨out Number⟩
(I know the upper bound: read Number, don’t write)"] --> C["MutableList⟨*⟩
(I know almost nothing: read Any?, don’t write)"]

Yes, this is a simplification (like all good teaching explanations), but it works great as intuition: the less you know about the type, the less Kotlin allows you to do.

7. Common mistakes when working with star-projection *

Mistake #1: thinking that List<*> is a “list of Any” and immediately calling element methods.
When you write val x: Any? = xs[0], and then try to do x.length, the compiler quite reasonably doesn’t understand why you decided it’s a string. The correct approach is a type check (if (x is String)) and only then working with string properties.

Mistake #2: trying to add elements to MutableList<*> and being surprised that you can’t even add null.
This is one of the most “frustrating” moments for a beginner, because it feels like null is universal. But MutableList<*> means that on writes it follows logic at the level of “in Nothing,” i.e., you can’t write anything type-safe (and null doesn’t fit either). If you need to add elements, then the function contract must use a concrete “input” type, for example MutableList<in Int> or MutableList<Any?>, not *.

Mistake #3: confusing MutableList<*> with MutableList<Any?> and choosing the asterisk “just in case.”
The asterisk isn’t “more universal,” it’s “stricter.” It’s perfect for “read/iterate/print” scenarios, but it’s inconvenient when you want to put something inside. If your function is supposed to fill the list, then you’re not in the * world, you’re in the in world.

Mistake #4: doing unsafe casts (as MutableList<String>) instead of using the asterisk just to “make it work.”
Sometimes it’s tempting to “force the compiler”: write as and move on. But with generics this often ends with the program compiling and then crashing at runtime in an unexpected place. List<*> and MutableList<*> are useful because they let you honestly say: “I don’t know the type” — and the compiler itself won’t let you perform dangerous operations.

Mistake #5: expecting the check x is List<*> to automatically give you knowledge about the element type.
That check only answers “is this a list or not.” After it, the elements will still be Any?, and that’s normal. If you need to understand whether it contains strings, numbers, or your Expense, you’ll have to check the elements (is String, is Int, is Expense) or build a different function contract where the type is known in advance.

1
Task
Kotlin SELF, level 36, lesson 3
Locked
Debug printout
Debug printout
1
Task
Kotlin SELF, level 36, lesson 3
Locked
Quick preview
Quick preview
1
Task
Kotlin SELF, level 36, lesson 3
Locked
Comment lengths
Comment lengths
1
Task
Kotlin SELF, level 36, lesson 3
Locked
Quick overview
Quick overview
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION