Kotlin Variables

Kotlin gives you two keywords, val and var, to declare variables with different mutability guarantees.

What Are Variables?

A variable is a named storage location that holds a value your program can read and, in some cases, update. In Kotlin, every variable must be declared using either the val or var keyword before it can be used, and the compiler infers or checks its type at compile time.

Declaring with val

Declaring read-only values with val

fun main() {
    val name = "Aditi"
    val age = 27
    val pi = 3.14159

    println("$name is $age years old")
    println("Pi is approximately $pi")
}

Declaring with var

Reassigning a var

fun main() {
    var score = 0
    println("Starting score: $score")

    score = 10
    score += 5
    println("Updated score: $score")
}

The difference between val and var is not about performance, it is about intent. A val reference can only be assigned once; attempting to assign it a second time is a compile-time error, not a runtime one. A var can be reassigned as many times as needed, as long as the new value matches the variable's declared type.

  • Start every declaration with val, then switch to var only if the compiler complains about reassignment.
  • Use var for loop counters, accumulators, and values that genuinely change over time.
  • Variable names should be camelCase and describe what the value represents, e.g. totalPrice, not tp.
  • Kotlin variables cannot be read before they are initialized, so always assign a value or a default before use.
Featurevalvar
ReassignmentNot allowed after first assignmentAllowed any number of times
Compiles to (JVM)Effectively a final fieldA regular mutable field
Typical useConstants, configuration, results of a computationCounters, accumulators, mutable state
Null safety interactionWorks with both nullable and non-null typesWorks with both nullable and non-null types

Type inference vs explicit typing

fun main() {
    val inferredInt = 42          // Kotlin infers Int
    val inferredDouble = 4.2      // Kotlin infers Double
    val explicitLong: Long = 42L  // explicit type annotation
    var explicitString: String = "hello"

    explicitString = "world"
    println("$inferredInt $inferredDouble $explicitLong $explicitString")
}
Note: Tip: Prefer val by default. Immutable references make code easier to reason about, especially once you start working with multiple threads or long functions where a value could otherwise change unexpectedly.
Note: Warning: Reassigning a val, such as writing val x = 1 followed by x = 2, produces the compiler error 'Val cannot be reassigned'. This is caught before your program ever runs, which is one of Kotlin's biggest safety advantages over languages where everything is mutable by default.

Exercise: Kotlin Variables

What is the key difference between val and var?