https://kotlinlang.org logo
Title
m

Mark

02/15/2020, 5:56 AM
Is there a better way to write
listOfStuff.asSequence().mapNotNull { fromStuffToSomethingOrNull(it) }.firstOrNull()
a

Andrew

02/15/2020, 6:20 AM
Probably not, depending how its used the asSequence part may not be needed, usually for lazy evaluation of lists. Since its doing firstOrNull its using lazy evaluation to get only the first item which might defeat the purpose.
m

Mark

02/15/2020, 6:53 AM
The
asSequence()
is there to avoid mapping all the items unnecessarily.
☝️ 2
m

molikuner

02/15/2020, 11:53 AM
I would at least factor it out to make the intend clear:
inline 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 }
👍 1
m

Mark

02/15/2020, 1:17 PM
And can apply to any iterable
inline fun <T, R: Any> Iterable<T>.firstMappedOrNull(noinline block: (T) -> R?): R? = asSequence().mapNotNull(block).firstOrNull()
Bonus points for naming it
firstMapNotNullOrNull()
😉
😂 1
👍🏻 2
d

Dico

02/16/2020, 8:58 PM
for (i in list) return block(i) ?: continue
return null
👍 1
m

molikuner

02/16/2020, 9:03 PM
Nice!
m

Mark

02/17/2020, 3:32 AM
It’s clever, but I don’t think as readable because
return block(i) ?: continue
is confusing. You have to work out that
block(i) ?: continue
will be evaluated first and so potentially avoid the return.
d

Dico

02/17/2020, 11:21 AM
Then rewrite it to be clearer, it's peanuts
You can start by puttimg the expression after the return in parentheses, and you can then move the return into a .let {} on the following line, or expand the if block and make a variable.
block(i)?.let { return it }
perhaps
m

Mark

02/17/2020, 12:24 PM
But now it’s less clear than
asSequence().mapNotNull(block).firstOrNull()
d

Dico

02/18/2020, 12:17 AM
I don't think subjective discussions are helpful