Mark
02/15/2020, 5:56 AMlistOfStuff.asSequence().mapNotNull { fromStuffToSomethingOrNull(it) }.firstOrNull()
Andrew
02/15/2020, 6:20 AMMark
02/15/2020, 6:53 AMasSequence()
is there to avoid mapping all the items unnecessarily.molikuner
02/15/2020, 11:53 AMinline fun <T, R : Any> List<T>.firstMappedNotNull(block: (T) -> R?): R? = asSequence().mapNotNull(block).firstOrNull()
Also I come up with an other implementation, but I definitely prefer yours, because it’s easier to read and understand.
inline fun <T, R : Any> List<T>.firstMappedNotNull(block: (T) -> R?): R? = forEach { block(it)?.also { return it } }.let { null }
Mark
02/15/2020, 1:17 PMinline fun <T, R: Any> Iterable<T>.firstMappedOrNull(noinline block: (T) -> R?): R? = asSequence().mapNotNull(block).firstOrNull()
Bonus points for naming it firstMapNotNullOrNull()
😉Dico
02/16/2020, 8:58 PMfor (i in list) return block(i) ?: continue
return null
molikuner
02/16/2020, 9:03 PMMark
02/17/2020, 3:32 AMreturn block(i) ?: continue
is confusing. You have to work out that block(i) ?: continue
will be evaluated first and so potentially avoid the return.Dico
02/17/2020, 11:21 AMblock(i)?.let { return it }
perhapsMark
02/17/2020, 12:24 PMasSequence().mapNotNull(block).firstOrNull()
Dico
02/18/2020, 12:17 AM