val declares a read-only reference, like const, and var a reassignable one, like let; prefer val and reach for var only when a value must change. Kotlin also fixes each variable's type at compile time:
const val CURRENCY = "USD" // compile-time constant, top level only
fun main() {
val title = "The Quiet Harbor" // read-only reference, like const
var stock = 3 // reassignable, like let
stock -= 1
title = "Salt and Saffron"
stock = "two"
val cart = mutableListOf(title) // the reference is fixed, the list is not
cart.add("Gardens in Glass")
println("$cart, $stock left, prices in $CURRENCY")
}Output
vals.kt:6:5: error: 'val' cannot be reassigned. ... vals.kt:7:11: error: assignment type mismatch: actual type is 'String', but 'Int' was expected. ...
Without lines 6 and 7 it prints [The Quiet Harbor, Gardens in Glass], 2 left, prices in USD. As with a const array, val cart fixes the reference, not the contents; the type says whether the list can change, since listOf() returns a read-only List and mutableListOf() a MutableList (Collections). const val goes further: a compile-time primitive or String, copied into every place that uses it.