覆盖数据类中的值

Mah*_*ara 0 oop android properties kotlin data-class

我尝试以下代码时遇到java.lang.StackOverflowError错误:堆栈大小8MB,应用程序恰好崩溃了1次,现在又不再崩溃了,我想知道这是否会引起任何问题提交此代码之前的未来

以下是本部分中使用的接口/数据类的示例

interface y{
    val image
}

data class x(val anotherImage): y{
    override val image
        get() = image ?: anotherImage
}
Run Code Online (Sandbox Code Playgroud)

我在这里想要的是让val图像包含图像的URL,有时后端在图像中返回它,而在其他时候在anotherImage中返回它,这就是为什么我写了这段代码,这里使用接口是为了与这个问题无关的问题

jsa*_*mol 5

您正在使用自定义getter中的实际属性名称来递归访问属性。Kotlin提供了field标识符,该标识符应用于在其访问器中引用该属性的值:

val image
    get() = field ?: anotherImage

Run Code Online (Sandbox Code Playgroud)