Type Inference (Kotlin)

Type inference lets the Kotlin compiler deduce a variable's or function's type from context, so you can omit explicit type annotations while keeping full static type safety.

Kotlin

When you write val x = 5, the compiler infers Int; val name = "hi" infers String. Single-expression functions infer their return type too: fun double(n: Int) = n * 2 returns Int. This keeps code concise without sacrificing the safety of static typing.

Inference is local and based on the initializer or expression, so a variable still has one fixed type once inferred. You add explicit annotations when there's no initializer, when you want a broader type (e.g. a List<Number>), or to document a public API's return type.

Because Kotlin is statically typed under the hood, inferred types are checked at compile time exactly like written ones — you get IDE autocompletion and error checking, just with less boilerplate than Java.

Syntax

val count = 42           // inferred Int
fun greet() = "hello"    // inferred String

Examples

Kotlin

val pi = 3.14159          // Double
val items = listOf(1, 2)  // List<Int>
fun square(n: Int) = n * n // returns Int
println(square(6))

Output:

36

Learn it in a lesson

See also

Back to the Dictionary