Hello guys, hope you can help me with this. I have...
# getting-started
a
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
Copy code
fun delete(id: UUID) = if (list.removeIf { it -> it.id == id }) Unit else throw NotFoundException(id)
💥 1
👍 1
a
Thank you so much, I didn’t know that we can return Unit as a value
e
or
Copy code
fun delete(id: UUID) { takeIf { list.removeIf { it -> it.id == id } } ?: throw NotFoundException(id) }
👍 1
p
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