Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

kotlin

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.

like image 699
Martin Drozdik Avatar asked Sep 15 '17 16:09

Martin Drozdik


People also ask

What does init block do in Kotlin?

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.

What will run first INIT block or secondary constructor?

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.


1 Answers

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 */     } } 
like image 172
hotkey Avatar answered Sep 28 '22 03:09

hotkey