Variable definition
Kotlin has two types of variables - read-only and variables with mutable values. Read-only variables are defined with the keyword "val" when mutable variables are defined with the keyword "val".
To define a variable, you have to provide a keyword identifying the variable as read-only or mutable, then specify the variable's type and then the variable's name.
val name: String = "John" var age: Int = 23
If you define the variable's value in the expression, you can omit the type because the compiler will recognize the type from the assigned value.
val name = "John" var age = 23
Constants
In Kotlin, constants are defined with the keywords "const val".
const val systemName = "My Super System"
Because you specify the value for constant, you can omit the type.
It seems we have a read-only variable, so what is the difference between a read-only variable and a constant?
The main difference is that constant value should be defined at compile time. Because of this, the constant can't be assigned a function call or constructor.
Comments powered by CComment