https://kotlinlang.org logo
#getting-started
Title
# getting-started
a

Antonio Acuña Prieto

05/25/2022, 6:55 PM
Hello guys, hope you can help me with this. I have a function that deletes an element of a list, something like:
fun delete(id: UUID) = list.removeIf { it -> it.id == id }
And I want to: • If the element was removed, don’t return nothing. • If the element was not found, return exception For now I have something like:
fun delete(id: UUID) = takeIf { list.removeIf { it -> it.id == id } } ?: throw NotFoundException(id)
But this still returns a true.
v

Vampire

05/25/2022, 7:07 PM
Copy code
fun delete(id: UUID) = if (list.removeIf { it -> it.id == id }) Unit else throw NotFoundException(id)
💥 1
👍 1
a

Antonio Acuña Prieto

05/25/2022, 7:10 PM
Thank you so much, I didn’t know that we can return Unit as a value
e

Endre Deak

05/25/2022, 7:12 PM
or
Copy code
fun delete(id: UUID) { takeIf { list.removeIf { it -> it.id == id } } ?: throw NotFoundException(id) }
👍 1
p

phldavies

05/25/2022, 7:57 PM
why not
Copy code
fun delete(id: UUID) { 
    if (!list.removeIf { it.id == id }) throw NotFoundException(id) 
}
Not sure using
takeIf
gains you anything here, nor does having both cases on the if to allow for using an expression-body function
👍 4
5
2 Views