Why is the "return" not allowed in the Kotlin init block?

If I compile this:

class CsvFile(pathToFile : String)
{
    init 
    {
        if (!File(pathToFile).exists())
            return
        // Do something useful here
    }
}

I get an error message:

Error: (18, 13) Kotlin: it is not allowed to return here

I do not want to argue with the compiler, but I am interested in learning about the motivation for this limitation.

+4
source share
1 answer

This is not allowed due to possible anti-intuitive behavior with respect to several blocks init { ... }, which can lead to subtle errors:

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

If the answer is no, the code becomes fragile: adding returnto one block initwill affect the other blocks.

, init, - :

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

:

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

Source: https://habr.com/ru/post/1685763/


All Articles