plusOrNull

fun Long.plusOrNull(other: Long): Long?

Long arithmetic that answers null instead of wrapping.

Kotlin's +, - and * on Long wrap silently past Long.MAX_VALUE, and the JDK's Math.addExact family is not available on Kotlin/Native or wasmJs. A tally that wrapped would report a number nobody ever counted, so code that cannot afford one routes through these and decides for itself what an overflow means: a typed refusal, a fallback, or a throw.

A null here always means the exact result does not fit in a Long. It never means anything else, so a.plusOrNull(b) ?: return Refused is a complete check.

Samples

assertEquals(7L, 3L.plusOrNull(4L))
assertNull(Long.MAX_VALUE.plusOrNull(1L))
assertNull(Long.MIN_VALUE.negateOrNull())