Hey, do we have a map function but where I can “sk...
# announcements
g
Hey, do we have a map function but where I can “skip” returning elements depending on some condition? Kind of a reduce?
g
mapNotNull
don’t work with nullable of course, but usually fine for most cases
g
Thanks, will check that!
s
of course, the general way would be to first run a filter and than a map. Regarding special cases: next to the useful
mapNotNull
, there is also the very useful
filterIsInstance
(if you want to only work with all the instances of the original list, that are of a specific subtype) https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/filter-is-instance.html
r
IMO the general way is to always
fold
since all other methods can be derived from
fold
, including
filter
and
map
. If you want to filter and map at the same time that is frequently known as
mapFilter
. It’s not in the std lib but the generalised version for all
Iterable
may look like:
Copy code
fun <A, B: Any> Iterable<A>.mapFilter(f: (A) -> B?): List<B> =
  flatMap { a -> listOfNotNull(f(a)) }

fun main() {
  val evenBy100: List<String> = listOf(1,2,3,4,5).mapFilter {
    if (it % 2 == 0) "$it * 100"
    else null
  }
  println(evenBy100) //[200, 400]
}
Implies you can filter and transform to new values of different types and
null
signals the ones you want to skip
g
Thank you!
👍 1
i
@raulraja That
mapFilter
is exactly what
mapNotNull
does
1