Kotlin lazy property depending on another property

2019-02-25 22:18发布

问题:

I have the following class in Kotlin:

class Example {
    val name: String

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

    init {
        name = "StackOverflow"
    }
}

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?

回答1:

Try

class Example {
    val name: String

    init {
        name = "StackOverflow"
    }

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


标签: kotlin