Android – what is the correct location for initializing class variables in kotlin

A: initialize the class variables in the 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: Class variables are initialized directly in class blocks

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

What is the difference between the two codes? Why?

resolvent:

There is no difference between the execution of these options a and B: Property initializers (assign values immediately) and initialization blocks (use init blocks). However, for simple initialization like code, you usually use property initializers in your case - option B

However, if you use these two versions in your code, please pay attention to the execution order of the initialization program

From this article:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>