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
相关产品推荐
相关产品推荐

