← Back to Kotlin Course | Chapter 2: Variables & Types | Lesson 2 of 7

Type Inference

Type inference means Kotlin is smart enough to figure out what kind of value a variable holds without you having to say so.

How Inference Works

When you write val age = 25, Kotlin looks at the value 25 and infers that age has type Int, without you writing Int anywhere. This happens at compile time, so the type is fixed and checked just as strictly as if you had written it.

Example: How Inference Works

markup
fun main() {
    val age = 25
    val price = 19.99
    val name = "Kotlin"
    println("$name costs $price for someone aged $age")
}

Explicit Type Annotations

You can always write the type explicitly after a colon, such as val age: Int = 25. This is required when there is no initial value to infer from, and can also improve readability in some cases.

Example: Explicit Type Annotations

markup
fun main() {
    val age: Int = 25
    val price: Double = 19.99
    println("Age: $age, Price: $price")
}

Inference and Static Typing

Even though the type is not always written, Kotlin remains statically typed: once inferred, a variable's type cannot change, and assigning a mismatched type is a compile-time error.

Note: Trying score = "high" after this would fail to compile -- the inferred type Int is locked in.

Example: Inference and Static Typing

markup
fun main() {
    var score = 100 // inferred as Int
    score = 105     // fine, still an Int
    println("Score: $score")
}

When Inference Is Not Possible

A val or var declared without an initial value has no basis for inference, so an explicit type is required in that case, and the variable must be assigned before it is used.

Example: When Inference Is Not Possible

markup
fun main() {
    val result: Int
    result = 10 * 4
    println("Result: $result")
}
Common Mistakes
  1. Believing Kotlin is dynamically typed because you rarely write out types explicitly; Kotlin is statically typed, it just infers types at compile time.
  2. Leaving a val uninitialized and expecting Kotlin to infer a type anyway; inference needs an initial value to work from.
  3. Adding redundant explicit types everywhere out of habit, making code more verbose than necessary.
Chapter Summary
  • Kotlin infers a variable's type from its initial value at compile time, not at runtime.
  • Kotlin is statically typed -- every variable has a fixed type, even when that type is not written explicitly.
  • Type inference requires an initializer; val x alone with no value cannot be inferred.
  • Explicit type annotations are still useful for clarity or when there is no initializer to infer from.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.