在 Kotlin 集合中找不到项目时抛出自定义异常

Tur*_*rzo 1 collections kotlin

我想从列表中查找一个人,否则抛出 PersonNotFoundException 。

在这种情况下,函数first()kotlin.collections抛出NoSuchElementException异常,但我想抛出我的自定义异常,即 PersonNotFoundException。

目前我正在使用以下逻辑:

val persons: List<Person> = listOf(...)
val name: String = "Bob"

persons.firstOrNull {
    it.name == name
}.let {
  it ?: throw PersonNotFoundException("No person was found with name $name")
}
Run Code Online (Sandbox Code Playgroud)

但我对此不太满意。感觉这个用例有一些我不知道的现有功能。

谁能帮我改进它吗?

Swe*_*per 5

你甚至不需要let。它所做的只是let让您使用 来引用找到的东西it

代码可以缩短为更惯用的形式:

persons.firstOrNull {
    it.name == name
} ?: throw PersonNotFoundException("No person was found with name $name")
Run Code Online (Sandbox Code Playgroud)