gpt4 book ai didi

android - 在 kotlin 中初始化类变量的正确位置是什么

转载 作者:IT老高 更新时间:2023-10-28 13:42:38 34 4
gpt4 key购买 nike

A:在init block 中初始化类变量

private class ViewHolder(view: View) {
val menuImg: ImageView
val txtMenu: TextView

init {
menuImg = view.find(R.id.menuImg)
txtMenu = view.find(R.id.txtMenu)
}
}

B:直接在类 block 中初始化类变量

 private class ViewHolder(view: View) {
val menuImg: ImageView = view.find(R.id.menuImg)
val txtMenu: TextView = view.find(R.id.txtMenu)
}

两个代码有什么不同,为什么?

最佳答案

这些选项 A 和 B 的执行没有区别:属性初始化器(立即赋值)和初始化器 block (使用 init block )。但是对于像您的代码这样的简单初始化,通常使用 Property 初始化程序——在您的情况下是选项 B。

但如果您在代码中同时使用这两个版本,请注意初始化程序的执行顺序。

引自 this article :

First, default constructor arguments are evaluated, starting with argument to the constructor you call directly, followed by arguments to any delegated constructors. Next, initializers (property initializers and init blocks) are executed in the order that they are defined in the class, top-to-bottom. Finally, constructors are executed, starting with the primary constructor and moving outward through delegated constructors until the constructor that you called is executed.

关于android - 在 kotlin 中初始化类变量的正确位置是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45673830/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com