Type Inference
In this page:
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
fun main() {
val age = 25
val price = 19.99
val name = "Kotlin"
println("$name costs $price for someone aged $age")
}
Login to try C/C++/Java/PHP code in the editor
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
fun main() {
val age: Int = 25
val price: Double = 19.99
println("Age: $age, Price: $price")
}
Login to try C/C++/Java/PHP code in the editor
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
fun main() {
var score = 100 // inferred as Int
score = 105 // fine, still an Int
println("Score: $score")
}
Login to try C/C++/Java/PHP code in the editor
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
fun main() {
val result: Int
result = 10 * 4
println("Result: $result")
}
Login to try C/C++/Java/PHP code in the editor
- Believing Kotlin is dynamically typed because you rarely write out types explicitly; Kotlin is statically typed, it just infers types at compile time.
- Leaving a
valuninitialized and expecting Kotlin to infer a type anyway; inference needs an initial value to work from. - Adding redundant explicit types everywhere out of habit, making code more verbose than necessary.
- 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 xalone 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: