Prefer val over var

When to use val

To define an immutable variable–that is, a constant or a value—use val, like so:

val pi: Double = 3.14

Unlike Java, where you’d place the type before the name of the variable, in Kotlin you place the name of the variable first, then a colon, followed by the type. Kotlin considers the sequence Java requires as “placing the cart before the horse” and places a greater emphasis on variable names than variable types.

Since the type of the variable is obvious in this context, we may omit the type specification and ask Kotlin to use type inference:

val pi = 3.14

Either way, the value of pi can’t be modified; val is like final in Java. Any attempt to change or reassign a value to variables defined using val will result in a compilation error. For example, the following code isn’t valid:

val pi = 3.14
pi = 3.14 //ERROR: val cannot be reassigned

When to use var

What if we want to be able to change the value of a variable? For that, Kotlin has var—also known as “keyword of shame.” Variables defined using var may be mutated at will.

Here’s a script that creates a mutable variable and then modifies its value:

var score = 10
//or var score: Int = 10
println(score) //10 score = 11
println(score) //11

Mutating variables is a way of life in imperative style of programming. But that’s a taboo in functional programming. In general, it’s better to prefer immutability—that is, val over var. Here’s an example to illustrate why that’s better:

Get hands-on with 1400+ tech skills courses.