val / var
val declares a read-only variable (immutable), and var declares a reassignable variable (mutable). The type is inferred from the initial value, so it can be omitted in most cases.
Syntax
// Declares a read-only variable (immutable). val variableName: Type = value val variableName = value // Type inference // Declares a reassignable variable (mutable). var variableName: Type = value var variableName = value // Type inference
Syntax Overview
| Keyword | Description |
|---|---|
| val | Declares a read-only variable. The reference cannot be reassigned, but the internal state of the referenced object can be modified. |
| var | Declares a reassignable variable. You can assign a different value to it later. |
| Type inference | When an initial value is provided, Kotlin automatically determines the type. This allows you to omit type annotations and keep your code concise. |
| lateinit var | Declares a non-null var whose initialization is deferred. Used for class properties that are initialized after the constructor. |
Sample Code
fun main() {
// val is read-only and cannot be reassigned.
val name: String = "Kotlin"
val version = 2.0 // Inferred as Double.
println(name) // Prints "Kotlin".
println(version) // Prints "2.0".
// Attempting to reassign a val causes a compile error.
// name = "Java" // Error: Val cannot be reassigned
// var can be reassigned.
var count = 0
count = count + 1
count += 1
println(count) // Prints "2".
// You can also write the type annotation explicitly.
var score: Int = 100
score = 200
println(score) // Prints "200".
// Even with val, you can modify the contents of a list (only the reference is immutable).
val numbers = mutableListOf(1, 2, 3)
numbers.add(4) // This is OK.
println(numbers) // Prints "[1, 2, 3, 4]".
}
Notes
In Kotlin, it is recommended to prefer val by default and use var only when reassignment is necessary. Using immutable variables proactively helps prevent unexpected bugs caused by unintended value changes. Because type inference is available, type annotations are typically written only when you want to make the intent explicit or when the initial value is set later.
For variable types, see Basic Data Types. For nullable types, see Nullable Types / ?. Operator.
If you find any errors or copyright issues, please contact us.