Hello ! I would like to do something on a list, i ...
# announcements
l
Hello ! I would like to do something on a list, i think there is a function i don't know but i don't find it... Here is my code :
Copy code
val stringList = somethingList.map {
   it.str
}

if (stringList.isNotEmpty()) {
   doSomethingWithMyList(stringList)
}
And i would like to do something like that
Copy code
somethingList.map {
   it.str
}.unknownOperation { // here i need help
   doSomethingWithMyList(it)
}
m
also
?
So:
Copy code
somethingList.map { it.str }
             .also { doSomething(it) }
l
I have already seen i can use something like :
Copy code
.also {
 if (isNotEmpty()) {
   doSomethingWithMyList(it)
  }
}
but i just would like to know if there is an operator or another way to do the apply and if not empty
I have created an extension function for doing it
Copy code
fun <T> List<T>.doIfNotEmpty(action: (List<T>) -> Unit): List<T> = also {
        if (isNotEmpty()) {
            action(this)
        }
    }
And i use it like
Copy code
somethingList.map {
  it.str
}.doIfNotEmpty { doSomethingWithMyList(it) }
I'm not sure it's the cleanest way to do
g
you can also use
.takeIf { it.isNotEmpty() }?.let{ doSomething(it)}
l
Thanks, didn't know takeIf 👍