Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Throw custom exception when item not found in a Kotlin collection

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading