Why is `return` not allowed in Kotlin init block?

This is not allowed because of possible counter-intuitive behavior with regard to several init { ... } blocks, which might lead to subtle bugs:

class C {
    init { 
        if (someCondition) return
    }
    init {
        // should this block run if the previous one returned?
    }
}

If the answer is ‘no’, the code becomes brittle: adding a return in one init block would affect the other blocks.

A possible workaround that allows you to finish a single init block is to use some function with lambda and a labeled return:

class C {
    init {
        run {
            if (someCondition) return@run
            /* do something otherwise */
        }
    }
}

Or use an explicitly defined secondary constructor:

class C {
    constructor() { 
        if (someCondition) return 
        /* do something otherwise */
    }
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)