In Kotlin, which is Google’s most preferred language for Android Development, there are various keywords used to declare variables. In this shot, we’ll go over the difference among each of these keywords and the best instances to use each of them.
var
var name = "peter"
var name: String = "peter"
var
is used to declare a mutable variable. A mutable variable is a variable that can be changed or that can be reassigned in the course of the program.
In the example above, both lines of code are basically the same, except that the data type is indicated in the second line.
Unlike Java, indicating the data type is optional in Kotlin, as Kotlin can infer the data type of the variable according to the value assigned to it. In var
, values are assigned during run time.
val
val
is used to declare immutable variables. Once a value is assigned to a variable with the val
keyword, it cannot be altered or reassigned throughout the program. Val
is similar to the final
keyword in Java.
val age = 35
Throughout the program, it is expected that the value of age
will remain 35
. If you try to assign another value to age
, an error will be thrown.
val
is also a run-time constant, meaning its value has to be assigned during run time.
const
const
is also used to declare variables that do not change in the course of the program, but const
is a compile-time constant, meaning its value has to be assigned at compile-time, unlike var
and val
. Since const
needs to know its value at compile-time, you cannot assign functions or constructors to it because the values of functions are determined at run-time.
const
is mostly declared at the top of the file as follows:
const val language = "en"
You can also declare const
in an object as follows:
object Website {
const val URL = "google"
}
The object
keyword is just like the static
keyword in Java. object
makes it possible to access that variable anywhere in your program.
In summary:
var | val | const |
---|---|---|
A variable declared with `var` is mutable. | A variable declared with `val` is immutable. | A variable declared with `const` is immutable. |
Values are assigned at run time. | Values are assigned at run time. | Values are assigned at compile time. |
A variable declared with `var` can be assigned primitive data types. | A variable declared with `val` can be assigned primitive data types. | A variable declared with `const` can be assigned primitive data types. |
A variable declared with `var` can be assigned a function. | A variable declared with `val` can be assigned a function. | A variable declared with `const` cannot be assigned to a function. |
Free Resources