Mahmoud Omara
Mahmoud Omara

Reputation: 665

Override a val in data class

I got an error of java.lang.StackOverflowError: stack size 8MB when I tried this bit of code and the app crashed exactly 1 time and now it doesn't crash again, I would like to find out if this would cause any problems in the future before committing to this code

Below are examples of the interface/data class used in this part

interface y{
    val image
}

data class x(val anotherImage): y{
    override val image
        get() = image ?: anotherImage
}

What I want here is to have the val image contain the URL of an image, sometimes the back-end returns it in image and other times in anotherImage and that's why I wrote that bit of code, the use of an interface here is for another problem irrelevant to this issue

Upvotes: 0

Views: 643

Answers (1)

jsamol
jsamol

Reputation: 3232

You are recursively accessing the property using the actual property's name in your custom getter. Kotlin provides the field identifier which should be used to reference the property's value in its accessors:

val image
    get() = field ?: anotherImage

Upvotes: 5

Related Questions