kotlin var and val
Kotlin provides two keywords for declaring variables: var
and val
.
var
is used to declare a mutable variable, which means its value can be changed after it is initialized. Here's an example:
var name: String = "John"
name = "Mike" // Valid, the value of name can be changed
In this example, the variable name
is declared using var
and assigned an initial value of "John". Later, the value of name
is changed to "Mike", which is allowed because name
is mutable.
On the other hand, val
is used to declare an immutable variable, which means its value cannot be changed once it is assigned. Here's an example:
val age: Int = 25
age = 30 // Invalid, the value of age cannot be changed
In this example, the variable age
is declared using val
and assigned an initial value of 25. Later, attempting to change the value of age
to 30 results in an error because age
is immutable.
To summarize, var
is used for mutable variables, allowing their values to be changed, while val
is used for immutable variables, preventing their values from being changed after initialization.