Does anyone have preferred ways to handle when you...
# codingconventions
s
Does anyone have preferred ways to handle when you either want a thing, or that same thing with some action applied to it? Or a name for that pattern.
Copy code
val distinct: Boolean
val list: List<T>
val maybeDistinct = if (distinct) list.distinct() else list
It's similar to
takeUnless
, but without the intermediary null, which makes it kind of ridiculous
Copy code
val maybeDistinct = list.takeUnless { distinct } ?: list.distinct()
I could write an extension function, something like
Copy code
val maybeDistinct = list.transformIf(distinct) { it.distinct() }
…which in this case is just as verbose, but has nicer signaling, imo. Maybe there's a stdlib function like this that I don't know about?
Not totally sure if this counts as a coding convention, but there's no #idioms
h
There's #codereview – I'd say, the simple
if
is the winner: Cleanest, easiest to understand and shortest code!
☝️ 1
s
I'll do #codereview next time, thanks. In this simple example I think I agree with you. But— It doesn't chain as nicely. You need a
Copy code
.let { if (distinct) it.distinct() else it }
vs
Copy code
.transformIf(distinct) { it.distinct() }
(also, could be a shorter name, like
applyIf
or
mapIf
)
It's also more awkward with longer variable names or if you need a line wrap. Here's a real-world usage I'm looking at
Copy code
private fun moveFavouritesToFront(originalList: List<DisplayItem<I>>): List<DisplayItem<I>> {
    return if (originalList.size > itemsPerRow && moveFavoritesToFront) {
        favs.moveLastPickedDisplayItemsToFront(javaClass.simpleName, originalList, originalList)
    } else {
        originalList
    }
}
vs something like
Copy code
private fun moveFavouritesToFront(originalList: List<DisplayItem<I>>): List<DisplayItem<I>> {
    originalList.transformIf(originalList.size > itemsPerRow && moveFavoritesToFront) {
        favs.moveLastPickedDisplayItemsToFront(javaClass.simpleName, it, it)
    }
}
The easiest for me to follow would be
Copy code
if (!distinct) list else list.distinct()
but this requires inverting the condition :/
because,
Copy code
private fun moveFavouritesToFront(originalList: List<DisplayItem<I>>): List<DisplayItem<I>> {
    return if (!(originalList.size > itemsPerRow && moveFavoritesToFront)) originalList
        else favs.moveLastPickedDisplayItemsToFront(javaClass.simpleName, originalList, originalList)
}
is good too, except for the awkward inversion
e
#stdlib
y
I've personally defined a
letIf
function sometimes that does practically the same thing.