Skip to content

Sum of null values #936

Answered by Jolanrensen
zueblin asked this question in Q&A
Oct 29, 2024 · 1 comments · 1 reply
Discussion options

You must be logged in to vote

It works as intended. The sum operation "ignoring" null values means it interprets them as the zero-value of the type you give it. So since you create a column of Int?, the zero value becomes 0.

If we don't do this by default it's ambiguous what "summing nulls" means. This is also why in the standard library, there are no .sum() functions for nullable iterables, just .sumOf {} which expects you to replace nulls.

So, if you expect "all nulls" to become null, you could write something like:
val sumOrNull: Int? = if (age_int.allNulls()) null else age_int.sum()

or as extension function on a DataColumn:

fun <C : Number> DataColumn<C?>.sumOrNull(): C? =
    if (allNulls()) null else sum()

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@zueblin
Comment options

Answer selected by zueblin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants