Difference Between var and val in Kotlin

1. Introduction

In Kotlin, var and val are keywords used to declare variables. Understanding the distinction between them is crucial for proper Kotlin programming. The var keyword declares a mutable variable - one that can be changed after it's initialized. The val keyword, on the other hand, declares an immutable variable, meaning once it's assigned a value, it cannot be changed.

2. Key Points

1. Mutability: var is mutable, val is immutable.

2. Initialization: Both var and val must be initialized before use, but var values can be changed later.

3. Best Practices: Using val is recommended for variables that don’t need to be modified, as it enhances readability and maintains immutability.

4. Use in Functions: val is often used for values that are meant to remain constant throughout the function, while var is used for values that need to change.

3. Differences

Characteristic Var Val
Mutability Mutable (can be changed) Immutable (cannot be changed)
Initialization Can be reassigned Cannot be reassigned after initialization
Best Practices Use when value changes Use for constant values
Use in Functions For changing values For constant values

4. Example

// Example of Var
var mutableName: String = "John"
mutableName = "Doe" // Allowed

// Example of Val
val immutableName: String = "Jane"
immutableName = "Doe" // Error: Val cannot be reassigned


Var Output:
Initial name: John, Changed name: Doe
Val Output:
Compilation error on trying to change the name


1. mutableName is declared with var and can be reassigned to "Doe" after initialization.

2. immutableName is declared with val and attempting to change its value results in a compilation error.

5. When to use?

- Use var for variables whose values are expected to change during the execution of a program.

- Use val for declaring variables whose values are not meant to change after initialization, to maintain immutability and improve code readability.