You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin集合查找元素未找到时,如何抛出自定义PersonNotFoundException?

优化方案

Kotlin标准库确实没有直接提供带自定义异常的first变体,但可以通过以下几种方式优化你的代码,兼顾可读性和复用性:

1. 通用扩展函数(推荐,复用性强)

给List<T>写一个通用扩展函数,让所有列表类型都能复用“找不到就抛自定义异常”的逻辑:

fun <T> List<T>.firstOrThrow(predicate: (T) -> Boolean, exceptionSupplier: () -> Throwable): T {
    return firstOrNull(predicate) ?: exceptionSupplier()
}

使用时非常简洁:

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

val targetPerson = persons.firstOrThrow(
    predicate = { it.name == name },
    exceptionSupplier = { PersonNotFoundException("No person was found with name $name") }
)

2. Person专属扩展函数

如果只需要在Person列表上使用这个逻辑,可以写针对性更强的扩展,调用时更直观:

fun List<Person>.findByNameOrThrow(name: String): Person {
    return firstOrNull { it.name == name } ?: throw PersonNotFoundException("No person was found with name $name")
}

使用方式:

val targetPerson = persons.findByNameOrThrow("Bob")

3. 简化原有写法(不新增函数)

如果不想额外写扩展函数,也可以直接简化原有代码的结构,去掉冗余的let:

val targetPerson = persons.firstOrNull { it.name == name } 
    ?: throw PersonNotFoundException("No person was found with name $name")

这种写法比原有的let链式调用更直接,可读性也更好。

内容的提问来源于stack exchange,提问作者Turzo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 04:40:18