如果我编译这个:
class CsvFile(pathToFile : String)
{
init
{
if (!File(pathToFile).exists())
return
// Do something useful here
}
}
Run Code Online (Sandbox Code Playgroud)
我收到一个错误:
错误:(18,13)Kotlin:这里不允许"返回"
我不想与编译器争论,但我很好奇这个限制背后的动机.
hot*_*key 21
这是不允许的,因为对于几个init { ... }块可能存在反直觉的行为,这可能会导致细微的错误:
class C {
init {
if (someCondition) return
}
init {
// should this block run if the previous one returned?
}
}
Run Code Online (Sandbox Code Playgroud)
如果答案为"否",则代码变得脆弱:return在一个init块中添加会影响其他块.
允许您完成单个init块的可能解决方法是使用一些带有lambda和标记返回的函数:
class C {
init {
run {
if (someCondition) return@run
/* do something otherwise */
}
}
}
Run Code Online (Sandbox Code Playgroud)
或者使用显式定义的辅助构造函数:
class C {
constructor() {
if (someCondition) return
/* do something otherwise */
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3090 次 |
| 最近记录: |