cbn*_*cbn 2 null try-catch kotlin
我有以下代码:
val targetImage: TargetImage?
try
{
targetImage = someFunctionThatCanThrowISE()
}
catch (e: IllegalStateException)
{
targetImage = null
}
Run Code Online (Sandbox Code Playgroud)
编译器说“无法重新分配val”,我可以看到可能是在try块中设置了targetImage之后,其他一些代码行(此示例中未显示)可能会抛出ISE。
在Kotlin的try-catch中,将val设置为某个值(为null或其他值)的最佳实践是什么?在当前情况下,如果我删除了捕获中的集合,它将使targetImage保持未设置状态,并且据我所知,没有办法测试未设置的值,因此在此代码块之后无法使用targetImage。我可以将val更改为var,但我不希望targetImage重新分配。
Kotlin中的try块是一个表达式,因此您可以将try / catch的值设置为targetImage ...
val targetImage: TargetImage? = try {
someFunctionThatCanThrowISE()
} catch (e: IllegalStateException) {
null
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您不想在字段声明的中间进行try / catch,则可以调用一个函数。
val targetImage: TargetImage? = calculateTargetImage()
private fun calculateTargetImage(): TargetImage? = try {
someFunctionThatCanThrowISE()
} catch (e: IllegalStateException) {
null
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
456 次 |
| 最近记录: |