https://kotlinlang.org logo
#stdlib
Title
# stdlib
p

Peter

03/07/2023, 12:27 PM
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

Riccardo Lippolis

03/07/2023, 12:32 PM
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

wasyl

03/07/2023, 12:36 PM
I sometimes just add nulls and to
filterNotNull()
later, but I agree this case is surprisingly common for me
j

Javier

03/07/2023, 12:37 PM
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

Rob Elliot

03/07/2023, 4:10 PM
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

wasyl

03/07/2023, 4:15 PM
It's both odd and pollutes the extensions space for all types 😕
p

Peter

03/07/2023, 7:39 PM
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

elect

03/08/2023, 8:02 AM
I'd rename `addIfNotNull`though
3 Views