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?