galex
05/28/2019, 9:34 AMgildor
05/28/2019, 9:35 AMmapNotNull
gildor
05/28/2019, 9:36 AMgalex
05/28/2019, 9:39 AMStephan Schroeder
05/28/2019, 10:31 AMmapNotNull
, 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.htmlraulraja
05/28/2019, 11:42 AMfold
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:
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]
}
raulraja
05/28/2019, 11:44 AMnull
signals the ones you want to skipgalex
05/28/2019, 1:17 PMilya.gorbunov
05/28/2019, 2:15 PMmapFilter
is exactly what mapNotNull
does