Kotlin惰性属性,取决于在init中初始化的另一个属性 [英] Kotlin lazy property depending on another property initialized in init

查看:105
本文介绍了Kotlin惰性属性,取决于在init中初始化的另一个属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在科特林有以下课程:

I have the following class in Kotlin:

class Example {
    val name: String

    val lazyVar: String by lazy {
        name + " something else"
    }

    init {
        name = "StackOverflow"
    }
}

lazyVar的惰性初始化块中使用name时,我得到以下错误(即使nameinit块中被初始化):

I get the following error when I use name in the lazy initialize block of lazyVar (even though name is initialized in the init block) :

变量名称"必须初始化

Variable 'name' must be initialized

一种解决方案是用另一种方法初始化变量:

A solution is to initialize the variable in another method:

class Example {
    val name: String

    val lazyVar: String by lazy {
        initLazyVar()
    }

    init {
        name = "StackOverflow"
    }

    private fun initLazyVar(): String {
        return name + " something else"
    }
}

这项技术有效,但是有办法保持内联惰性块的兼容性而不是依赖于外部函数吗?

This technique works but is there a way to keep the compacity of the inline lazy block instead of relying on an external function?

推荐答案

尝试

class Example {
    val name: String

    init {
        name = "StackOverflow"
    }

    val lazyVar: String by lazy {
        name + " something else"
    }
}

这篇关于Kotlin惰性属性,取决于在init中初始化的另一个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆