liveBook · Manning

Type inference

As explained in Kotlin in Action, 2E

Type inference is the compiler's ability to determine expression types without requiring explicit type annotations everywhere.

Type inference lets the Kotlin compiler determine an expression’s type from context, so static typing need not mean annotating every variable. An initializer such as an integer literal supplies enough information for Kotlin to infer `Int`, retaining compile-time type knowledge while removing repetitive declarations. section 1.2.2 section 1.6

val x: Int = 1    #1
val y = 1         #2

Both declarations create an `Int`; the second relies on the initializer instead of spelling out the type. section 1.2.2

For initialized variables, omit a type when the initializer makes intent clear. Kotlin analyzes that expression: `42` yields `Int`, while a floating-point constant yields `Double`. Explicit types remain useful when they clarify the declaration or when inference has no initializer to inspect. section 2.1.4

val question =
   "The Ultimate Question of Life, the Universe, and Everything"
val answer = 42

The question and answer declarations infer `String` and `Int` from their initializer expressions. section 2.1.4

fun main() {
   val answer: Int
   answer = 42
}

A variable assigned later needs an explicit type because no initializer is available for inference. section 2.1.4

Inference also applies to generic type arguments. Calling `listOf` with only strings produces a `List<String>` without repeating `String`. An empty collection provides no element type, so supply it either on the variable declaration or on the collection-creation function. section 11.1

val readers: MutableList<String> = mutableListOf()

val readers = mutableListOf<String>()

These equivalent empty-list declarations show the two places an otherwise uninferable generic type can be stated. section 11.1

Unlike Java raw types, Kotlin requires generic type arguments to be known—either written explicitly or inferred. This keeps concise declarations tied to a definite type rather than an unspecified collection element type. section 11.1 section 1.4.2

How Kotlin in Action, 2E covers it

How deep it goes
Explains inference from variable initializers and generic collection arguments, including cases where missing information requires explicit types.
Examples
Uses inferred `Int`, `String`, and `Double` variables plus string lists and explicitly typed empty mutable lists.
What you can do after
Apply it via Kotlin variable declarations and collection creators to omit types the compiler can deduce.
How it connects
Connects static typing, variable declarations, generic type parameters, collection-creation functions, and Java raw types.

Also explained in

Compare how 16 books explain type inference →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.