From time to time I have to work with nullable numbers in Kotlin. Kotlin has a lot of instuments for working with nullable types, but I believe it lacks support of arithmetic operations on them.
For instance, consider the following snippet:
var a: Double? = 10.0
var b: Double? = 20.0
var c = if (a != null && b != null) a / b else null
Here we need to check both variables for null before applying division - too much code
The situation gets worse when operands are mutable fields
class Test {
var a: Double? = null
var b: Double? = null;
var c: Double? = null;
}
class TestService() {
fun calculateValues(test: Test) {
val a = test.a
val b = test.b
if (a != null && b != null)
test.c = a / b
}
}
My suggestion is to add arithmetic operators, that can accept nullable arguments and return null if one of the arguments is null: something like that
var a: Double? = 10.0
var b: Double? = 20.0
var c = a /? b
and
class TestService() {
fun calculateValues(test: Test) {
test.c = test.a /? test.b
}
}