Hey guys, I have a really random question about op...
# random
o
Hey guys, I have a really random question about operator for collections in Kotlin. Is there something like
if not empty let
? I’m always doing like below and I really wish to drop this local variable if possible.
Copy code
val items = getItems()
if(items.isNotEmpty()) {
  doSomethingWith(items) // e.g map items etc..
}
I have a solution with using
takeIf
Copy code
getItems().takeIf { it.isNotEmpty() }?.let {
  doSomethingWith(it) // e.g map items etc..
}
but is there any better solution?
k
Ideally this problem doesn't happen because
doSomethingWith
handles empty collections as well.
o
You’re right when
doSomethingWith
is the method for each items but when it comes to do something with list
isNotEmpty
is needed.
k
Can you give an example? Now I'm curious.
s
agree with Karel, why can't doSomethingWith handle empty lists?
o
Well simple example is like you want to print items when there are items (don’t want to print if there were no items). What happened the most recent was I had to build headers for request and this is done if only there were valid headers. It might be rare but I think there are some use cases for handling theses empty or not.
s
okay so lets say do something is println, you dont want anything such as [] sent to screen when empty
I 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)
you could make an extension on List but i cant see why you would
r
Could also use
firstOrNull()
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.
Just ignore the return value if it isn’t null
o
Through this conversation, I kind a agree with what Matt said
I 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