If I compile this:
class CsvFile(pathToFile : String) { init { if (!File(pathToFile).exists()) return // Do something useful here } }
I get an error:
Error:(18, 13) Kotlin: 'return' is not allowed here
I don't want to argue with the compiler, but I am curious about the motivation behind this restriction.
Kotlin initThe code inside the init block is the first to be executed when the class is instantiated. The init block is run every time the class is instantiated, with any kind of constructor as we shall see next. Multiple initializer blocks can be written in a class. They'll be executed sequentially as shown below.
The constructor is the secondary constructor. Delegation to the primary constructor happens as the first statement of a secondary constructor, so the code in all initializer blocks is executed before the secondary constructor body.
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 */ } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With