Values and variables in Kotlin
val for bindings that never move, var for the few that must.
fun main() {
// val binds once; var may be reassigned. Types are inferred.
val ridge = "Sawtooth"
var hikers = 4
hikers += 2
// Spell a type out when inference would pick the wrong one.
val distanceKm: Double = 12.0
val perLeg = distanceKm / hikers
println("$hikers on $ridge, ${"%.1f".format(perLeg)} km each")
}
How it works
val ridgecannot be reassigned;var hikerscan, and+=updates it.- Types are inferred everywhere the initializer makes them obvious.
distanceKm: Doublespells one out so the division stays fractional.
Keywords and builtins used here
Doublefunmainvalvar
The run, in numbers
- Lines
- 11
- Characters to type
- 314
- Tokens
- 59
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 51 seconds.
Step 2 of 3 in Values, step 2 of 27 in Language basics.