Cannot return in init?

class HelloWorld(int: Int?) {
    init {
        if(int == null) 
            return       // 'return' is not allowed here
    }
}

class HelloWorld {
    constructor(int: Int?) {
        if(int == null)
            return        // This is fine
    }
}

Is there a way to return in init? or I am forced to use constructor?

1 Like

Alternatively you can write it so that you don’t need the return:

class HelloWorld(int: Int?) {
    init {
        int?.let {
            // Do something with int
        }
    }
}

Kotlin’s constructors are possibly the worst language construct I’ve ever encountered. Stuffing a bunch of constructor logic into the class header is horrible because it absolutely kills code readability. Having a separate init block is also horrible because it separates init logic from the constructor. And unfortunately yes, Kotlin does NOT allow the return keyword to appear within an init block.

I work around the ridiculous return limitation by doing a silly time-wasting hack:

init {
    properInit()
}

private fun properInit() {
    return //ha!
}
2 Likes