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

Variables declared as one data type and then initialized with a value of the wrong type will result in an error.

var myVariable: Int = b //ERROR! as b is different type

val variables must be assigned at declaration, or in a Classconstructor.

class Address(val street: String) {

val name: String = "Kotlin"

}

private lateinit var myViewModel: MyViewModel
myViewModel = MyViewModel()

You cannot use val for lateinit variable as it will be initialized later on. Also you must guarantee that you are initializing the variable before using the variable otherwise it will throw exception at runtime. You cannot use lateinit for primitive type properties like Int, Long etc.

Accessing a lateinit property before it has been initialized throws a special exception that clearly identifies the property being accessed and the fact that it hasn't been initialized.

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

If variable are mutable (i.e. might change at a later stage) use lateinit

lateinit var can be initialized from anywhere the object is seen from.

lazy can only be used for val properties, whereas lateinit can only be applied to var because it can’t be compiled to a final field, thus no immutability can be guaranteed.

If its only meant to initialized once and shared by all, and it’s more internally set (dependent on variable internal to the class), then use lazy.

val inferredType = 1 // has type Int and a default getter
val updateLiveData: LiveData<Boolean>
get() = isUpdateLiveData
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