A mutable variable in Kotlin, declared using theDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
var keyword, is a memory location whose stored value or object reference can be reassigned after its initial declaration. Unlike read-only variables (val), a var permits continuous state mutation throughout its lifecycle within its lexical scope.
Syntax
The standard syntax requires thevar keyword, an identifier, an optional explicit type declaration, and an assignment.
Technical Characteristics
Strict Static Typing While the value of avar can change, its data type is statically bound at compile time. Reassigning a value of a different, non-conforming type results in a compilation error.
var depends heavily on its declaration context:
- Local Variables: When declared inside a function, a
varcompiles to a standard, non-final local variable in Java bytecode. - Top-level Properties: When declared outside of any class or interface, a
varcompiles to a private static field accompanied by static getter and setter methods within a generated file-level facade class (e.g.,FilenameKt). - Class Properties: When declared as a member of a class, a
vargenerates agetterand asettermethod. The visibility of these accessors matches the property’s visibility modifier (e.g., aprivate vargenerates private accessors). Furthermore, a setter’s visibility can be independently restricted (e.g., usingprivate seton a public property). A private backing field is generated in memory only if at least one accessor uses the default implementation, or if a custom accessor explicitly references thefieldidentifier. Properties with fully custom getters and setters do not generate a backing field.
var property exposes a mutator (setter), Kotlin allows developers to override the default set() function to intercept and manipulate the reassignment process. The field identifier is used to safely access the generated backing field without triggering recursive setter calls.
lateinit modifier. This modifier can be applied to class properties, top-level properties, and local variables. This contract promises the compiler that the var will be assigned a reference before its first memory access, thereby avoiding the need to declare the type as nullable (?). The lateinit modifier is exclusively compatible with var and cannot be applied to primitive types (e.g., Int, Double).
Master Kotlin with Deep Grasping Methodology!Learn More





