How to convert Long to Int in Kotlin?

Use Long.toInt():

process((System.currentTimeMillis() / 1000 / 60).toInt()) 

↓Long.toInt() is not safety. because long to int is shrink

val l: Long
l.toInt() ←not safety! when out of int range

Please add this function to arbitrary kt file instead. Then, a method called toIntOrNull is added to Long. This method returns null if it tries to convert long to int, when it does not fit within int range.

fun Long.toIntOrNull(): Int? {
    return if (this < Int.MIN_VALUE || this > Int.MAX_VALUE) {
        null
    } else {
        this.toInt()
    }
}

or

fun Long.toIntOrNull(): Int? {
    val i = this.toInt()
    return if (i.toLong() == this) i else null
}

Tags:

Kotlin