nwh
07/28/2021, 12:17 AMfirstNotNullOfOrNull
? I have seen an increasing number of these functions appearing and they always strike me as excessive and obtuse - this one in particular still does not make sense to me, even after some soul seeking. It's a combination of firstOrNull
and mapNotNull
, the latter of which is itself a "convenience" for filterNotNull().map { ... }
. Where does it end? Should we have firstNotNullOfOrNullIsInstanceOf
? I feel like I'm missing something here.
To me, seeing this in code explains a lot more conceptually, and I don't see what's "wrong" with it:
data.map { String.toDoubleOrNull(it) }.filterNotNull().firstOrNull()
ephemient
07/28/2021, 12:56 AMrnett
07/28/2021, 1:04 AMnwh
07/28/2021, 1:06 AMSequence
? There's just no way to avoid excessive list creations for all possible combinations of mapping, filtering, finding, selecting, etc. when using Iterables.
IMO, these methods create a bit of an anti-pattern as they try to support more and more niche use cases. If performance is key, a Sequence
should be used.ephemient
07/28/2021, 1:58 AMdata.firstNotNullOfOrNull { if (it == 5) return "special case" else ... }
ephemient
07/28/2021, 2:02 AMnwh
07/28/2021, 4:03 AMephemient
07/28/2021, 4:32 AM.firstNotNullOfOrNull()
is different than .mapNotNull().firstOrNull()
, and JB uses it enough to deem it worthy of addition to stdlib. similarly, at least in my code, .mapNotNull()
is definitely common enough that it's worth having a shortcut for it over .filter().map()
or .map().filterNotNull()
. if it didn't exist, we'd have written our own, as we have with some things like .applyIf()
etc.ephemient
07/28/2021, 4:36 AM*indexed*()
iterable methods too (e.g. there's currently no .allIndexed()
, .joinToStringIndexed()
, etc.)ephemient
07/28/2021, 4:37 AM.reduce()
or .foldRight()
methods useful - .fold()
and .reduceOrNull()
are enough - but it's also not harming anything