I am roughly 2 weeks fresh into Kotlin, I had been heavily interested in functional programming and I was not sure on this part if I miss a fundamental idiom in FP as I wanted to handle boilerplate like retrieving results from a repository, if the result is an empty list then I want a log statement and want other chained calls to stop. In general, why are there (at least not obvious to me) not functions that deal with empty lists? Like below? Asking the question, I probably can leave out the "this" null check.
fun <E : Any, T : List<E>> T?.ifEmpty(func: () -> Unit): List<E> {
if (this == null || this.isEmpty()) {
func()
return emptyList()
}
return this
}
fun <E : Any, T : List<E>> T?.ifNotEmpty(func: (List<E>) -> Unit): List<E> {
if (this != null && !this.isEmpty()) {
func(this)
return this
}
return emptyList()
}
fun <E : Any, F: Any, T : List<E>> T?.mapIfNotEmpty(func: (List<E>) -> (List<F>)): List<F> {
if (this != null && !this.isEmpty()) {
return func(this)
}
return emptyList()
}
ifEmpty is available since Kotlin 1.3 (kotlin.collections).
ifNotEmpty
Looks like useless function, most often we iterate over the lists and if that lists are empty our code won't execute. So, e.g.
list.ifNotEmpty { do sth with whole list. sth like iteration? mapping? }
has same effect like
list.forEach { do sth with only one element and nothing if list is empty }
list.map { map every element to other object }
And if it is not enough then You can just write sth like this:
list.takeIf { it.isNotEmpty() }?.apply|let // unfortunately it looks ugly
mapIfNotEmpty Same story, for e.g.
listOf<String>("ab", "cd").mapIfNotEmpty { it.reversed() }
listOf<String>("ab", "cd").map { it.reversed() }
has exactly same result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With