Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Correct place to initialize class variables in kotlin

Tags:

android

kotlin

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 ?.

like image 701
Mahmood Ali Avatar asked Aug 14 '17 11:08

Mahmood Ali


1 Answers

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.

like image 198
Bob Avatar answered Oct 06 '22 00:10

Bob