英文:
How to initialize lateinit var with 'by keyword' in kotlin
问题
我想要使用 'by' 来初始化 lateinit 变量。
如何做?
lateinit var test: int
fun main() {
test by something {} // 错误!
}
我尝试在 by lazy 中使用 by,并尝试在 lateinit var 中使用 by,但都不起作用。
英文:
I want to initialize lateinit variable with 'by'.
How can I?
lateinit var test: int
fun main() {
test by something {} // error!
}
I tried using by in by lazy, and I tried using by in lateinit var, but it didn't work.
答案1
得分: 2
你在使用 by lazy
时不需要 lateinit
。"Lazy" 意味着它将在第一次被引用时初始化。而 lateinit
意味着你需要在构建后的某个时刻手动分配一个值。
所以,你只需要这样:
val test by lazy { something() }
fun main() {
println(test) // 运行初始化并打印值
}
更新:
或者,如果你想初始化一个现有的 lateinit
属性:
lateinit var test: Type
fun main() {
val something by other
test = something
}
英文:
You don't need lateinit
when using by lazy
. Lazy means it'll be initialized the first time it's referenced. lateinit
means you manually assign a value some time after construction.
So all you need is
val test by lazy { something() }
fun main() {
println(test) // runs the initializer and prints the value
}
Update:
Or, if you want to initialize an exising lateinit
property:
lateinit var test: Type
fun main() {
val someting by other
test = something
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论