Anyone else uses something like this: ```fun <...
# stdlib
p
Anyone else uses something like this:
Copy code
fun <T> MutableCollection<T>.addNotNull(elem: T?): Boolean {
    return if (elem !== null) add(elem) else false
}
I find it keeps my code more clean than all the
if (elem !== null) { collection.add(elem) }
boilerplate statements. I was always surprised it doesn’t come with stdlib already (or I couldn’t find it).
2
2
r
I usually just do something like
elem?.let { collection.add(it) }
in that case. Probably the hassle of having to maintain this function if it's added to the stdlib outweighs the benefit of not having to define the function in case you want it 🙂 (as the implementation is pretty straightforward)
w
I sometimes just add nulls and to
filterNotNull()
later, but I agree this case is surprisingly common for me
j
I think this is too short to add a shortcut for it
Copy code
elem?.let(collection::add)

// vs

collection.addNotNull(elem)
2
👍 4
👍🏻 1
r
collection.addNotNull(elem)
is much easier to read though...
2
Spitballing but what about:
Copy code
fun <X> X.addTo(xs: MutableList<X>) {
    xs.add(this)
}

elem?.addTo(collection)
Null handling is one of my favourite reasons for extension functions, but in this case it's a bit odd the way it reverses the natural order of
elem
and
collection
...
w
It's both odd and pollutes the extensions space for all types 😕
p
Didn’t consider
elem?.let(collection::add)
Besides readability (although I guess depends how “functionally minded” you are) the difference is that the returned type is a Boolean? and not a Boolean. But anyway don’t require that feature.
e
I'd rename `addIfNotNull`though