Type Inference
Kotlin works out a variable's type from the value you assign, so you write the type only when there is no initial value or when you want a different type than the one inferred.
Inspect inferred types and identify where an explicit type clarifies a boundary.
Kotlin is strict about types: a number of cups is never confused with a customer name. Yet most Kotlin code barely mentions types at all. That is because the compiler reads the value you assign and works out the type itself.
The rule
The value names the type; write it only when there is no value.
val cups = 3 // Int
val price = 3.5 // Double
val tip = 0.5f // Float, because of the f
val beansSold = 3L // Long, because of the L
val cafe = "Pebble Café" // String
val isOpen = true // BooleanThe type is fixed at compile time, even though you did not write it. Hover over cups in the IDE and it shows Int. Later, cups = "three" would still be an error (and cups is a val anyway).
When do you write the type?
- No initial value.
val openingHour: Intneeds a type because there is nothing to infer from. - You want a different type than the default.
val total: Long = 5stores a small number as aLong. - Clarity at a boundary. Public functions often spell out their return type so readers do not have to guess.
Inference also works for expressions. val bill = cups * price is a Double, because an Int times a Double gives a Double. A function with an expression body infers its return type too:
fun double(n: Int) = n * 2 // returns Int