Sum of null values #936
-
When calculating the sum of a column containing only null values, the result is 0. To me this seems wrong.
Output:
The documentation states that the sum operation ignores null values. I would expect the result to be null instead of 0. Thanks for you ideas! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
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 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 So, if you expect "all nulls" to become or as extension function on a fun <C : Number> DataColumn<C?>.sumOrNull(): C? =
if (allNulls()) null else sum() |
Beta Was this translation helpful? Give feedback.
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 becomes0
.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
: