Search code examples
androidkotlincomputed-properties

computed property declared using val vs using var


I have a question about the difference between the following 2 ways to create a computed property for class in kotlin.

for the code below, doesn't it break what val is meant for, i.e. a val variable should refer to a Int that should not change?

val currentQuestionResId: Int // way 1
    get() = questionBank[qIdx].textResId

var currentQuestionResId: Int // way 2
    get() = questionBank[qIdx].textResId

Doing it in way 2, the compiler complains and asks me to initialize my variable, which also kind of does not make sense, because there is getter it can use to get its first value the next line.

enter image description here


Solution

  • Doing it in way 2, the compiler complains and asks me to initialize my variable, which also kind of does not make sense, because there is getter it can use to get its first value the next line.

    • "way 2" defines the property as var.
    • var means it's mutable and can be assigned and, since you did not define a custom set, there will be a backing field to hold the value when the set is called.
    • So, although you have defined a custom get which will be called when you read the property, internally in the class a variable exists that holds the value when you set the property. That variable is what is being initialized.

    With the "way 1" there is no setter and you've defined a custom getter, so there is no backing field and so the variable does not require initialization (since there is no actual internal variable to initialize).