Kotlin 是如何通过消除检查异常来实现类型安全的?
How does Kotlin achieve type-safety by eliminating checked exceptions?
我是 Kotlin 编程的新手。在回顾 Kotlin 相对于 Java 的优势时,我发现了这样一种说法,即通过避免检查异常,Kotlin 实现了类型安全。另外我不明白用空 catch 块处理的异常如何损害类型安全(我在博客上读过)?
可以举例说明吗?
就其本身而言,删除已检查的异常并不会提高类型安全性。 Kotlin 改进类型安全性的主张来自于它引入的其他功能和惯用语,以取代已检查的异常。
在 Kotlin 中,异常不适用于可恢复的故障。他们只是在那里处理错误和逻辑错误。
As a rule of thumb, you should not be catching exceptions in general Kotlin code.
[...]
Use exceptions for logic errors, type-safe results for everything else. Don’t use exceptions as a work-around to sneak a result value out of a function.
https://elizarov.medium.com/kotlin-and-exceptions-8062f589d07
上面提到的“类型安全结果”是像 sealed classes 这样的东西,它提供了一种非常可控的方式来枚举函数可以 return 的可能类型。例如,您可以有一个密封的 class,其中一个实现用于成功结果,其他实现用于每种可能的失败类型。
If there’s a single error condition and you are only interested in success or failure of the operation without any details, then prefer using null
to indicate a failure. If there are multiple error conditions, then create a sealed class hierarchy to represent various results of your function. Kotlin has all those needs covered by design, including a powerful when
expression.
https://elizarov.medium.com/kotlin-and-exceptions-8062f589d07
我是 Kotlin 编程的新手。在回顾 Kotlin 相对于 Java 的优势时,我发现了这样一种说法,即通过避免检查异常,Kotlin 实现了类型安全。另外我不明白用空 catch 块处理的异常如何损害类型安全(我在博客上读过)? 可以举例说明吗?
就其本身而言,删除已检查的异常并不会提高类型安全性。 Kotlin 改进类型安全性的主张来自于它引入的其他功能和惯用语,以取代已检查的异常。
在 Kotlin 中,异常不适用于可恢复的故障。他们只是在那里处理错误和逻辑错误。
As a rule of thumb, you should not be catching exceptions in general Kotlin code. [...] Use exceptions for logic errors, type-safe results for everything else. Don’t use exceptions as a work-around to sneak a result value out of a function.
https://elizarov.medium.com/kotlin-and-exceptions-8062f589d07
上面提到的“类型安全结果”是像 sealed classes 这样的东西,它提供了一种非常可控的方式来枚举函数可以 return 的可能类型。例如,您可以有一个密封的 class,其中一个实现用于成功结果,其他实现用于每种可能的失败类型。
If there’s a single error condition and you are only interested in success or failure of the operation without any details, then prefer using
null
to indicate a failure. If there are multiple error conditions, then create a sealed class hierarchy to represent various results of your function. Kotlin has all those needs covered by design, including a powerfulwhen
expression.https://elizarov.medium.com/kotlin-and-exceptions-8062f589d07