Variables in Kotlin – var, val, lateinit, lazy And getters & setters
Kotlin is a very compact language with smart mutability and immutability features. This post was made to explain how the variable definition works in Kotlin, so let’s start.
var
Kotlin’s keyword var representing non-final, fully mutable variables. Once initialized, we are welcome to change its value wherever we want. Let’s see at the following declaration:
var myVariable = 1 var mySecondVariable:Int = 2
The myVariable initializes with the Int data type. Kotlin also supports type inference, it means that we can define the type manually as well – look at mySecondVariable definition.
val
This keyword works very similar to var but has one major difference. Defined variable is read-only and immutable. The usage of val is like declaring a new variable with the final keyword. See the following example:
// Kotlin val name:String = "Cezary"
// Java final String name = "Cezary";
The key thing with val variables is that values must be assigned at declaration or in a Class constructor.
lateinit
Means late initialization. If you don’t want to set a value at the constructor and planning do it later, you can use lateinit. You must guarantee the initialization before using a variable. Kotlin will not allocate memory until you set a value.
private lateinit superModelObject:SuperModelClass
and after that, you can initialize a value somewhere in your class
superModelObject = SuperModelClass(parametrOne="Some value")
You must guarantee initialization of the variable before using it otherwise will throw an exception and also you cannot use lateinit for primitive data types such as Int, Long and so on.
lazy
It means lazy initialization. Your variable will not be initialized unless you use this variable in code. It will be initialized only once after that we always use the same value.
lazy() is a function that takes lambda and returns an instance of lazy. The first call to get() exetutes the lambda passed to lazy() and remembers the result and subsequent get() calls simply return the remembered value.
val example: String by lazy { "Some Value" } println(example)
lateinit vs lazy
If variable is mutable (might change in later stage) use lateinit; lateinit var can be initialized anywhere in code and must be initialized manually before later use.
lazy can only be used with val variables, so once initialized, has the same value.
getter
getters are used for receiving a value of the variable. Kotlin internally generates a getter for read-only variables. The getter is optional in kotlin. Variable type is optional if it can be inferred from the initializer.
setter
setters are used for assigning a value to the variable. Kotlin internally generates a default getter and setter for mutable properties like var. Property type is optional if it can be inferred from the initializer.
If you have any doubts, feel free to write a comment below, cheers 🙂