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.

    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).