Kotlin val vs var: read-only vs mutable variables
The commands on this page have not been executed by our verification runner yet.updated
- tool
- Kotlin
- compares
- val vs var
val declares a read-only variable: it is assigned exactly once and cannot be reassigned. var declares a mutable variable that can be reassigned any number of times. Use val by default and switch to var only when the value really has to change; reassigning a val is a compile error.
val name = "Ada" // read-only
var count = 0 // mutable
count += 1 // OK
// name = "Grace" // compile error: a val cannot be reassignedSide by side
| val | var | |
|---|---|---|
| Reassignment | Not allowed after initialisation | Allowed |
| Late initialisation | Can be assigned once later (val x: Int; x = 1) | Can be assigned at any time |
| As a class property | Generates a getter only | Generates a getter and a setter |
| Object it points to | Can still be mutable (e.g. a MutableList) | Can be mutable or not |
| Compile-time constant | const val (top level or in an object, primitives and String) | Not possible |
| Thread safety | Reference is safe to share once set | Needs synchronisation if shared |
val is a read-only reference, not an immutable object
val items = mutableListOf(1, 2)
items.add(3) // OK: the list changes, the reference does not
// items = mutableListOf() // not allowed: reassignment
val fixed = listOf(1, 2) // read-only List interface: no add()For data that must not change, combine val with read-only types (List, Map, Set) or immutable data classes whose properties are all val.
Properties
class User(val id: Int, var email: String)
val u = User(1, "a@example.com")
u.email = "b@example.com" // var property: has a setter
// u.id = 2 // val property: no setterA val property can still return different values if it has a custom getter (val isEmpty get() = size == 0), so val means "no setter", not "constant".
const val
const val defines a compile-time constant, inlined by the compiler. It is allowed only at top level, in an object or a companion object, and only for primitive types and String:
const val MAX_RETRIES = 3Sources
Related pages
errors · swiftSwift Fatal error: Unexpectedly found nil while unwrapping an Optional valueSwift crashes with this fatal error when ! force-unwraps an Optional that is nil, or an outlet is not connected. Use if let, guard let or ?? to handle nil.errors · javajava.lang.NullPointerException: Cannot invoke "String.length()" because "name" is nullJava's helpful NullPointerException names the call that failed and the null variable. Why it can say <local1> instead of a name, and how to fix the null.glossary · gradleWhat is the Gradle Wrapper (gradlew)?The Gradle Wrapper is a script plus a small JAR committed to a project that downloads and runs the exact Gradle version the build needs. How to use and upgrade.