https://kotlinlang.org logo
Title
r

Ran Magen

09/16/2019, 4:56 PM
you mean by using a
(T) -> (R?)
and then
mapNotNull
? That'd work (assuming
T : Any
) but it would create an intermediate list, which ideally I'd like to avoid.
e

Evan R.

09/16/2019, 5:11 PM
If you’re worried about intermediate lists, you may want to try
.asSequence()
. Then you can just do:
val sampleList = listOf(1, 2, 3)
val filterMappedList = sampleList.asSequence().filter { it > 1 }.map { it * 2 }.toList()
👍 1
💯 1
a

arekolek

09/16/2019, 8:41 PM
you mean by using a
(T) -> (R?)
and then
mapNotNull
?
No, I think Karel meant:
inline fun <T, R : Any> List<T>.collect(
        predicate: (T) -> Boolean,
        transform: (T) -> R
): List<R> {
    return mapNotNull {
        if (predicate(it)) {
            transform(it)
        } else {
            null
        }
    }
}
k

karelpeeters

09/16/2019, 10:35 PM
Yes @arekolek, that's what I meant, thanks! I usually do something like that but in-place of course.
👍 1