https://kotlinlang.org logo
Title
l

Louis

12/12/2018, 10:46 AM
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 :
val stringList = somethingList.map {
   it.str
}

if (stringList.isNotEmpty()) {
   doSomethingWithMyList(stringList)
}
And i would like to do something like that
somethingList.map {
   it.str
}.unknownOperation { // here i need help
   doSomethingWithMyList(it)
}
m

marstran

12/12/2018, 10:55 AM
also
?
So:
somethingList.map { it.str }
             .also { doSomething(it) }
l

Louis

12/12/2018, 10:57 AM
I have already seen i can use something like :
.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
fun <T> List<T>.doIfNotEmpty(action: (List<T>) -> Unit): List<T> = also {
        if (isNotEmpty()) {
            action(this)
        }
    }
And i use it like
somethingList.map {
  it.str
}.doIfNotEmpty { doSomethingWithMyList(it) }
I'm not sure it's the cleanest way to do
g

gsala

12/12/2018, 1:10 PM
you can also use
.takeIf { it.isNotEmpty() }?.let{ doSomething(it)}
l

Louis

12/12/2018, 1:21 PM
Thanks, didn't know takeIf 👍