为什么Kotlin init块中不允许“return”?

如果我编译这个:

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

我得到一个错误:

错误:(18,13)Kotlin:“返回”在这里是不允许的

我不想和编译器争论,但我对这个限制背后的动机感到好奇。

这是不允许的,因为可能与多个init { ... }块有反直觉行为,这可能会导致一些微妙的错误:

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

如果答案是“否”,则代码变得脆弱:在一个init块中添加一个return将影响其他块。

一个可能的解决方法,允许你完成一个单独的init块,使用lambda和带标签的return函数:

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

或者使用显式定义的二级构造函数 :

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