Kotlin var, val, lateinit, lazy, getters & setters

var

var, Kotlin’s keyword representing mutable, non-final variables. Once initialized, we’re free to mutate/change the data held by the variable.

val

val keyword works same as the var keyword, but with one key difference the variable is read-only/nonmutable. The use of val is like declaring a new variable in Java with the final keyword.

lateinit

lateinit means late initialization. If you do not want to initialize a variable in the constructor instead you want to initialize it later on and if you can guarantee the initialization before using it, then declare that variable with lateinit keyword. It will not allocate memory until initialized.

private lateinit var myViewModel: MyViewModel
myViewModel = MyViewModel()

lazy

It means lazy initialization. Your variable will not be initialized unless you use that variable in your code. It will be initialized only once after that we always use the same value.

val test: String by lazy {
val testString = "some value"
}

getter

getters are used for getting value of the property. Kotlin internally generates a getter for read-only properties using val. The getter is optional in kotlin. Property type is optional if it can be inferred from the initializer.

val inferredType = 1 // has type Int and a default getter
val updateLiveData: LiveData<Boolean>
get() = isUpdateLiveData

setter

setters are used for setting value of the property. Kotlin internally generates a default getter and setter for mutable properties using var. Property type is optional if it can be inferred from the initializer.

var initialized = 1 // has type Int, default getter and setter
var stringRepresentation: String
get() = this.toString()
set(value) {
setDataFromString(value)
// parses the string and assigns values to other properties
}
var setterVisibility: String = "abc"
private set // the setter is private and default implementation

--

--

Senior Android Engineer @Delivery Hero | Android developer | Kotlin lover | Flutter explorer | Problem Solver

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Md Ali Hossain

Md Ali Hossain

Senior Android Engineer @Delivery Hero | Android developer | Kotlin lover | Flutter explorer | Problem Solver