android koltin,如何检测Long溢出

android koltin, how to detect Long overflow

有两个Long需要相加,如何检测避免溢出?

fun add2Long(l1: Long, l2: long): Long {
    return l1 + l2
}

您可以使用 StrictMath.addExact。如果溢出

,它会抛出一个ArithmeticException
fun add2Long(l1: Long, l2: Long): Long = try {
    StrictMath.addExact(l1, l2)
} catch (e: ArithmeticException) {
    Long.MAX_VALUE // handle overflow
}