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.

Create a free account to save this page, take notes and track your progress. Sign in

val and var

  • val declares a read-only variable: it's assigned once.
  • var declares 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.

val and var
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.

Compile-time constants
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?

  1. val
  2. var
  3. const
  4. let
Show answer

Answer: var

Was this page helpful?