Is there a more functional approach to this? I don...
# codereview
Is there a more functional approach to this? I don't really like creating a new variable just to check if it is empty. Thanks guys!
Copy code
val newSmth = listOfObjects.filter { ... }
        if (newSmth.isNotEmpty()) {
If nothing better exists, I guess you keep your function cleaner/more readable with something like
Copy code
fun <E> List<E>.applyIfNotEmpty(action: (List<E>) -> Unit) {
        if(size > 0) {
so you can
Copy code
objs.filter { it == 'a' }
    .applyIfNotEmpty (otherWorkflow::process)
There might well be something nice OOTB though
listOfObjects.filter { … }.let { if (it.isNotEmpty()) otherWorflow.process(it) }
or even
listOfObjects.filter {…}.takeUnless { it.isEmpty() }?.let { otherWorkflow.process(it) }
depending on how much obfuscation you want to add 😉
👆 3
😂 3
if you want to be able to read that code again, I suggest going with your original solution 🙂
☝️ 5
Yeah, I will keep it as it is. Anyway, thanks for your ideas!
👋 1
@araqnid’s first reply looks best. On the other hand, what happens if you send an empty list to
? If that method iterates through a list, the nothing should happen when the list is empty, thus no need for the empty check. If the method crashes or does something weird when the parameter is an empty list, it is probably cleaner and safer to do the empty check within the method itself.
👍 1