omuomugin
02/19/2019, 9:04 AMif not empty let
? I’m always doing like below and I really wish to drop this local variable if possible.
val items = getItems()
if(items.isNotEmpty()) {
doSomethingWith(items) // e.g map items etc..
}
omuomugin
02/19/2019, 9:08 AMtakeIf
getItems().takeIf { it.isNotEmpty() }?.let {
doSomethingWith(it) // e.g map items etc..
}
but is there any better solution?karelpeeters
02/19/2019, 9:14 AMdoSomethingWith
handles empty collections as well.omuomugin
02/19/2019, 9:34 AMdoSomethingWith
is the method for each items but when it comes to do something with list isNotEmpty
is needed.karelpeeters
02/19/2019, 9:38 AMsitepodmatt
02/19/2019, 10:30 AMomuomugin
02/19/2019, 10:42 AMsitepodmatt
02/19/2019, 12:36 PMsitepodmatt
02/19/2019, 12:37 PMsitepodmatt
02/19/2019, 12:38 PMrook
02/19/2019, 3:08 PMfirstOrNull()
in this case. The name of the method doesn’t lend itself to readability for this case, but it does what you’re looking for.rook
02/19/2019, 3:09 PMomuomugin
02/19/2019, 3:38 PMI don’t think you can get anything more succinct or clearer than takeIf { predicate }.also { } (also for side effects or let if assigning to something on the left)Anyway thanks for having discussion for this random question