在Kotlin中初始化类变量的正确位置是什么 [英] What is the Correct place to initialize class variables in kotlin

查看:68
本文介绍了在Kotlin中初始化类变量的正确位置是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

A: initialize class variable in 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:直接在类块中初始化类变量

B: initialize class variable direct in class block

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

两个代码之间有何不同?为什么?

what different between two code and why ?.

推荐答案

这些选项A和B的执行没有区别: 属性初始化程序(立即分配一个值)和初始化程序块(使用init块).但是对于像您的代码这样的简单初始化,通常使用属性初始化程序-在您的情况下为选项B.

There is no difference in the execution of those options A and B: Property initializers (immediately assigning a value) and Initializer blocks (using init block). But for simple initializations like your code, it is common to use the Property initializer -- option B in your case.

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

But be aware of the execution order of the initializers if you use both versions in your code.

本文引用:

首先,评估默认的构造函数参数,从 您直接调用的构造函数的参数,后跟参数 给任何委托的构造函数.接下来,初始化程序(属性 初始化程序和init块)按照它们被执行的顺序执行 定义在类中,从上到下.最后,构造函数是 执行,从主要构造函数开始,然后向外移动 通过委托的构造函数,直到您调用的构造函数为止 被执行.

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.

这篇关于在Kotlin中初始化类变量的正确位置是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆