Бежан Александр
06/21/2019, 11:37 AMcollectFirst
for that. How to do it in Kotlin ?murphy
06/21/2019, 11:49 AMmapNotNull
with your partial transformation function and then firstOrNull
on the result.firstOrNull
with a predicate and then transform the result, if any.U75957
06/21/2019, 11:52 AMcollectFirst
murphy
06/21/2019, 11:52 AMbezrukov
06/21/2019, 11:53 AMlist.asSequence().filter { }.map { }.first()
murphy
06/21/2019, 11:59 AMcollectFirst
is also not hard to write, for example like this:
fun <T, R> Iterable<T>.collectFirst(transform: (T) -> R?) : R? {
for (i in this) {
val o = transform(i)
if (o != null) return o
}
return null
}
Pavlo Liapota
06/21/2019, 12:05 PMlist
.find { it % 2 == 0 }
?.let { abs(it) }
If you need separate lambdas for predicate and transformation, then one function call will not look nice:
list.collectFirst({ it % 2 == 0 }, { abs(it) })
murphy
06/21/2019, 12:07 PMБежан Александр
06/21/2019, 12:29 PMPavlo Liapota
06/21/2019, 12:47 PMinline
.murphy
06/21/2019, 12:49 PMasSequence
before mapNotNull
and firstOrNull
instead of a dedicated extension method would also avoid computing too many intermediate results.Бежан Александр
06/21/2019, 12:50 PMcollectFirst
extension function in anyway. Since I want this level of abstraction and don’t wanna know how it’s implemented.murphy
06/21/2019, 12:52 PMБежан Александр
06/21/2019, 12:52 PM