How do I idiomatically sum the size of multiple li...
# getting-started
e
How do I idiomatically sum the size of multiple lists that are nullable? E.g.
Copy code
val totalSize = (list1?.size ?: 0) + (list2?.size ?: 0)
I'm wondering if there is a more idiomatic, easier to read syntax
Maybe
Copy code
val totalSize = list1.orEmpty().size + list2.orEmpty().size
1
This doesn't allocate extra lists, since
orEmpty
references
internal object EmptyList
, which I use in many places, so it shouldn't incur an overhead, right?
👍 2
j
Would you first make a list of lists, then flatten it, then get the size? Something like
Copy code
listOfNotNull(list1, list2, list3).flatten().size
plus1 1
e
That would allocate a new list unnecessarily. I'd like to sum the sizes directly, but without all the parentheses and question marks from my original question. I'll stick with the empty list solution
j
Depends if you prefer clarity over efficiency I guess
e
True, but IMHO the clarity of adding sizes with a + operator is even better (than flattening a list of not nulls)
👍 1
Thanks for your answer!
👌 1
a
a slight adjustment @justin crow, to avoid the flattening :)
Copy code
listOfNotNull(list1, list2, list3).sumOf { it.size }
plus1 2
j
Nice 👍
a
if you want to try and de-deduplicate an operation, and make it prettier, you could define an extension property
Copy code
private val List<*>?.sizeOrZero: Int get() = this?.size ?: 0

fun main() {
  val list1: List<Int>? = listOf(1, 2, 3)
  val list2: List<Int>? = listOf(1, 2, 3)
  val list3: List<Int>? = listOf(1, 2, 3)

  list1.sizeOrZero + list2.sizeOrZero + list3.sizeOrZero
}
or a local function if the operation is only specific to a single function
Copy code
fun main() {
  val list1: List<Int>? = listOf(1, 2, 3)
  val list2: List<Int>? = listOf(1, 2, 3)
  val list3: List<Int>? = listOf(1, 2, 3)

  fun List<*>?.sizeOrZero(): Int = this?.size ?: 0

  list1.sizeOrZero() + list2.sizeOrZero() + list3.sizeOrZero()
}
(it has to be a fun, not a val - a restriction that might be lifted in the future?)
👍 1
j
Nice, I’m new to Kotlin and didn’t realise you could have local extension functions
e
Thanks Adam. Those are some nice extensions. Now it's a matter of choosing between sticking with the stdlib (
.orEmpty().size
) or an extension. In my case I'd put the extension in some common source, but that would pollute the namespace a bit too (not that this is a very specific extension, but more generally applicable). I'll have to discuss with my reviewers which of the two approaches would fit better in our code bases.