typestar

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

  1. val ridge cannot be reassigned; var hikers can, and += updates it.
  2. Types are inferred everywhere the initializer makes them obvious.
  3. distanceKm: Double spells one out so the division stays fractional.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Values, step 2 of 27 in Language basics.

← Previous Next →