Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: why do I need to initialize a var with custom getter?

Tags:

kotlin

Why do I need to initialize a var with a custom getter, that returns a constant?

var greeting: String // Property must be initialized  get() = "hello" 

I don't need initialization when I make greeting read-only (val)

like image 990
Lukas Lechner Avatar asked Jan 03 '17 09:01

Lukas Lechner


People also ask

How do I declare lateInit in Kotlin?

NOTE: To use a lateinit variable, your variable should use var and NOT val . Lateinit is allowed for non-primitive data types only and the variable can't be of null type. Also, lateinit variable can be declared either inside the class or it can be a top-level property.

How do you initialize lateInit property in Kotlin?

In order to create a "lateInit" variable, we just need to add the keyword "lateInit" as an access modifier of that variable. Following are a set of conditions that need to be followed in order to use "lateInit" in Kotlin. Use "lateInit" with a mutable variable. That means, we need to use "var" keyword with "lateInit".

Can we use lateInit with Val?

You cannot use val for lateinit variable as it will be initialized later on.

How do you use the Kotlin getter setter?

When you instantiate object of the Person class and initialize the name property, it is passed to the setters parameter value and sets field to value . Now, when you access name property of the object, you will get field because of the code get() = field . This is how getters and setters work by default.


2 Answers

Reason behind this is Backing field. When you create val with custom getter that does not use field identifier to access its value, then backing field is not generated.

val greeting: String     get() = "hello" 

If you do, then backing field is generated and needs to be initialized.

val greeting: String // Property must be initialized     get() = field 

Now with var. Since backing filed is generated by default, it must be initialized.

var greeting: String // Property must be initialized     get() = "hello" 

For this to work for var without initialization, you must provide a custom setter to prevent generation of backing field. For example:

var storage: String = "" var greeting: String     get() = "hello"     set(value) { storage = value} 
like image 145
Januson Avatar answered Sep 19 '22 14:09

Januson


Your code does not have a custom setter, so it is equivalent to:

var greeting: String     get() = "hello"     set(v) {field = v}  // Generated by default 

The default implementation of set uses field, so you've got to initialise it.

By the same logic, you don't have to init the field if nether your set nor get use it (which means they are both custom):

var greeting: String  // no `field` associated!     get() = "hello"     set(v) = TODO() 
like image 41
voddan Avatar answered Sep 21 '22 14:09

voddan