androidengineers.Book a session

Generics and Type Parameters

Type Inference tips & pitfalls

article15 minMedium

Inference works from available constraints

Kotlin infers types from initializers, arguments, expected return types, and generic bounds. When too little information exists, provide an explicit type at the boundary instead of inserting casts.

fun main() {
    val titles = emptyList<String>()
    val counts: MutableList<Int> = mutableListOf()
    counts.add(25)
    val mixed = listOf("Kotlin", 25)
    check(titles.isEmpty())
    println(mixed)
}

An empty collection provides no element examples, so an expected type or explicit argument is useful. Mixing unrelated values may infer a broad common type, which can make later domain operations unavailable. That is a design signal, not merely an inconvenience.

Explicit return types on public functions prevent accidental API changes when an implementation expression changes. Local variables can usually remain inferred when their meaning is obvious.

Exercise

Write a generic identity function and call it with null, a string, and a value stored as Any. Inspect the inferred results in the IDE.

Check: inference follows the declared information at the call site; it does not recover hidden domain meaning from runtime values.

Reference: Generics

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
Type Inference tips & pitfalls | Kotlin Core Programming | Android Engineers