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: 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 ?.
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.
Quoting from 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With