I want to find a person from a list, or throw a PersonNotFoundException otherwise.
The first()
function from kotlin.collections
throws NoSuchElementException
in this scenario, but I want to throw my custom exception i.e. PersonNotFoundException.
Currently I'm using the following logic:
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")
}
But I'm not quite satisfied with it. It feels that there is some existing function for this use case that I'm not aware of.
Can anyone help me improve it?
CodePudding user response:
You don't even need let
. All let
does is it lets you refer to the found thing using it
.
The code can be shortened to the more idiomatic:
persons.firstOrNull {
it.name == name
} ?: throw PersonNotFoundException("No person was found with name $name")