Type Inference
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 IntThe shortcut
Read the literal's shape, left to right:
- quotes
"…"→String; single quotes'…'→Char true/false→Boolean- a decimal point →
Double, unless it ends inf→Float - a whole number →
Int, unless it ends inLor is too big forInt→Long
val cups = 42A whole number with no suffix that fits in 32 bits:
Int.
A common surprise is val tip: Float = 0.5. The literal 0.5 is a Double, and Kotlin never converts it silently, so this fails. Write 0.5f.
Drills
Answer fast — trust the rule.
What type does Kotlin infer for val price = 4.0?
Which declaration is a compile error?
Why does val openingHour (with nothing else on the line) fail to compile?
val cups = 4 and val each = 2.5. What is the type of cups * each?
Remember
- The literal's shape decides the type: quotes, point, suffix, size.
- Write a type when there is no value or you want a non-default type.
0.5is Double; a Float needs0.5f.
