Kotlin Tutorial · Kotlin Basics · Lesson 4 of 31
Kotlin Variables: val and var
Declare read-only variables with val and mutable ones with var, and let type inference do the work.
val and var
valdeclares a read-only variable: it's assigned once.vardeclares a mutable variable that can be reassigned.
Prefer val; use var only when a value really changes. The type is inferred from the value, or you can
write it after a colon: val count: Int = 3.
fun main() {
val city = "Lisbon" // type inferred as String
var visitors = 10 // Int, can change
visitors += 5
val price: Double = 19.99 // explicit type
println("$city: $visitors visitors, ticket $price")
// city = "Porto" // error: val cannot be reassigned
}
Output
Lisbon: 15 visitors, ticket 19.99
Run this on your computer — see “Get Started” for setup.
Constants
const val declares a compile-time constant at the top level or inside an object; it must be a primitive or a
String.
const val MAX_USERS = 1_000
fun main() {
val signedUp = 870
println("Places left: ${MAX_USERS - signedUp}")
}
Output
Places left: 130
Run this on your computer — see “Get Started” for setup.
Test yourself
Which keyword declares a variable that can be reassigned?
valvarconstlet
Show answer
Answer: var