Erik
06/19/2023, 12:44 PMval totalSize = (list1?.size ?: 0) + (list2?.size ?: 0)
I'm wondering if there is a more idiomatic, easier to read syntaxErik
06/19/2023, 12:46 PMval totalSize = list1.orEmpty().size + list2.orEmpty().size
Erik
06/19/2023, 12:47 PMorEmpty
references internal object EmptyList
, which I use in many places, so it shouldn't incur an overhead, right?justin crow
06/19/2023, 1:02 PMlistOfNotNull(list1, list2, list3).flatten().size
Erik
06/19/2023, 1:04 PMjustin crow
06/19/2023, 1:05 PMErik
06/19/2023, 1:06 PMErik
06/19/2023, 1:07 PMAdam S
06/19/2023, 1:19 PMlistOfNotNull(list1, list2, list3).sumOf { it.size }
justin crow
06/19/2023, 1:20 PMAdam S
06/19/2023, 1:23 PMprivate 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
}
Adam S
06/19/2023, 1:25 PMfun 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?)justin crow
06/19/2023, 2:19 PMErik
06/19/2023, 2:28 PM.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.