如果我编译它:
class CsvFile(pathToFile : String)
{
init
{
if (!File(pathToFile).exists())
return
// Do something useful here
}
}
我收到错误:
错误:(18,13)Kotlin:'返回'这里不允许
我不想与编译器争论,但我对这种限制背后的动机感到好奇。
答案 0 :(得分:19)
这是不允许的,因为对于几个init { ... }
块可能存在反直觉行为,这可能会导致细微的错误:
class C {
init {
if (someCondition) return
}
init {
// should this block run if the previous one returned?
}
}
如果答案为“否”,则代码变得脆弱:在一个return
块中添加init
会影响其他块。
允许您完成单个init
块的可能解决方法是使用lambda和a labeled return的某些函数:
class C {
init {
run {
if (someCondition) return@run
/* do something otherwise */
}
}
}
或使用明确定义的secondary constructor:
class C {
constructor() {
if (someCondition) return
/* do something otherwise */
}
}