简体   繁体   中英

init block in Kotlin with 2+ constructors

Found that init {} block is executed before secondary constructor.

So basically i have two constructors ( primary and secondary ). Primary is used just for initializing simple view. Secondary - trying to populate editViews with data. After secondary constructor im expecting that init block will be executed.

Is there a way to make it happen?

class EditView(val context: Context){
    constructor(context: Context, title: String): this(context) {
        // Executes after init block
    }

    init {
        // Ran before secondary constructor
        // Code for initializing my view
    }
}

You can't do this, since the init blocks are essentially the body of the primary constructor (and so are any inline property initializers). This means that it will run when you call into the primary from the secondary with this(context) , and only then can you run the code in your secondary constructor.

Having ran the primary constructor first ensures that your instance is already in a valid, constructed state for when the primary constructor's body runs - for example, non-nullable properties have a non-null value, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM