androidengineers.Book a session

Generics and Type Parameters

Star Projections & Type Projections

article15 minMedium

Unknown element types still permit safe operations

A star projection means a generic argument is unknown, with operations restricted according to its bounds and variance. It does not mean you may insert arbitrary values.

fun describe(values: List<*>): String =
    values.joinToString { value -> value?.toString() ?: "null" }

fun copyNumbers(source: Array<out Number>): List<Double> =
    source.map { it.toDouble() }

Reading from List<*> yields values safe to treat as Any?. The out projection lets the array be used as a producer of numbers without allowing writes of an incompatible numeric subtype. Runtime type erasure means checking value is List<*> does not prove that every element is a string.

Exercise

Write a function that accepts List<*> and returns only string elements, then compare it with one that rejects the entire list if any element is not a string.

Check: these are different policies. Filtering malformed input must not be mistaken for validating that the original collection had the required type.

Reference: Star projections

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
Star Projections & Type Projections | Kotlin Core Programming | Android Engineers