Search code examples
kotlinnullable

What is the most readable way to sum two nullable Int in Kotlin?


I tried to do something like the following:

val a: Int? = 1
val b: Int? = 1

a?.plus(b)

but it doesn't compile cause plus expects an Int.

I also tried to create a biLet function:

fun <V1, V2, V3> biLet(a: V1?, b: V2?, block: (V1, V2) -> V3): V3? {
    return a?.let {
        b?.let { block(a, b) }
    }
}

and use it like that:

val result = biLet(a, b) { p1, p2 -> p1 + p2 }

but it seems a lot of work for something apparently simple. Is there any simpler solution?


Solution

  • Unfortunately there isn't anything already in the standard library to sum two nullable ints.

    What you can do, however, is to create an operator fun for a nullable Int?:

    operator fun Int?.plus(other: Int?): Int? = if (this != null && other != null) this + other else this ?: other
    

    And then, you can use it normally like the not-null version:

    val a: Int? = 2
    val b: Int? = 3
    val c = a + b
    

    If you don't want to create a function for it, you can always use its body to handle the nullability of the two ints.