How do I use val and var inside Kotlin classes?

In Kotlin classes, val and var are used to declare properties.

  • val means read-only after initialization
  • var means mutable / can be reassigned

Basic example

class User {
    val id: Int = 1
    var name: String = "Alice"
}

Usage:

fun main() {
    val user = User()

    println(user.id)      // 1
    println(user.name)    // Alice

    user.name = "Bob"     // OK: name is var

    // user.id = 2        // Error: id is val
}

val inside a class

Use val when the property should not be reassigned after it gets a value.

class Product {
    val sku: String = "ABC-123"
}

You can read it:

val product = Product()
println(product.sku)

But you cannot assign a new value:

// product.sku = "XYZ-999" // Not allowed

var inside a class

Use var when the property can change.

class Counter {
    var count: Int = 0

    fun increment() {
        count++
    }
}

Usage:

fun main() {
    val counter = Counter()

    counter.increment()
    counter.increment()

    println(counter.count) // 2
}

Declaring properties in the constructor

A common Kotlin style is to put properties directly in the class constructor.

class User(
    val id: Int,
    var name: String
)

This creates a class with:

  • a read-only id
  • a mutable name

Usage:

fun main() {
    val user = User(1, "Alice")

    println(user.id)
    println(user.name)

    user.name = "Bob" // OK

    // user.id = 2    // Error
}

Important distinction

If you write this:

val user = User(1, "Alice")

The variable user itself cannot point to another User, because it is a val.

But if the object has var properties, those properties can still change:

val user = User(1, "Alice")

user.name = "Bob" // OK, because name is var

// user = User(2, "Charlie") // Error, because user is val

So:

val user

means the reference cannot be reassigned.

var name

inside the class means the property can be changed.

Rule of thumb

Use val by default, and only use var when the value really needs to change.

class Person(
    val birthYear: Int,
    var displayName: String
)

Here, birthYear probably should not change, but displayName might.

How do I declare variables in Kotlin using val and var?

In Kotlin, you can declare variables using two keywords: val and var. The choice between them depends on whether you want the variable to be immutable or mutable.

1. Declaring Immutable (Read-Only) Variables with val

  • Use val when the value of the variable will not change after it is initialized.
  • The variable becomes read-only (similar to final in Java).

Syntax:

val variableName: Type = value

Example:

val name: String = "John"
// name = "Jane" // This will cause a compilation error

Kotlin can also infer the type automatically if it can be deduced from the value:

val age = 30 // Kotlin infers that 'age' is of type Int

2. Declaring Mutable Variables with var

  • Use var when the value of the variable can change during the program’s lifecycle.
  • The variable becomes mutable.

Syntax:

var variableName: Type = value

Example:

var age: Int = 25
age = 26 // This is allowed because 'age' is mutable

Similarly, type inference can be used:

var firstName = "John" // Kotlin infers that it's a String
firstName = "Jane" // Allowed because 'firstName' is mutable

Key Differences Between val and var

Aspect val var
Mutability Immutable (read-only) Mutable (modifiable)
Reassignment Not allowed Allowed
Use Case When a value should not change When a value needs to change

Additional Examples

Example 1: Declaring Variables with Explicit Types

val city: String = "New York"
var temperature: Double = 25.5
temperature = 30.0 // This is valid

Example 2: Using Type Inference

val country = "USA" // 'country' is inferred to be a String
var isRaining = false // 'isRaining' is inferred to be a Boolean
isRaining = true // Valid because 'isRaining' is mutable

Important Notes

  • For complex objects (like lists and maps), val does not mean the contents of the object cannot change; it just means the variable reference cannot be reassigned.
val list = mutableListOf(1, 2, 3)
list.add(4) // Allowed, because the contents of the list are mutable
// list = mutableListOf(5, 6, 7) // Not allowed, because 'list' is immutable
  • Try to prefer val over var wherever possible to make your code safer and easier to reason about.