Peter
03/07/2023, 12:27 PMfun <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).Riccardo Lippolis
03/07/2023, 12:32 PMelem?.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)wasyl
03/07/2023, 12:36 PMfilterNotNull()
later, but I agree this case is surprisingly common for meJavier
03/07/2023, 12:37 PMelem?.let(collection::add)
// vs
collection.addNotNull(elem)
Rob Elliot
03/07/2023, 4:10 PMcollection.addNotNull(elem)
is much easier to read though...Rob Elliot
03/07/2023, 4:13 PMfun <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
...wasyl
03/07/2023, 4:15 PMPeter
03/07/2023, 7:39 PMelem?.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.elect
03/08/2023, 8:02 AM