netimen
netimen

Reputation: 4419

How to convert Long to Int in Kotlin?

I want to do something like this:

fun process(minutes: Int) = 0

fun test() {
    process(System.currentTimeMillis() / 1000 / 60) // error: Int expected
}

and if I try process((System.currentTimeMillis() / 1000 / 60) as Int) I get a ClassCastException at runtime.

So how can I convert Long to Int?

Upvotes: 33

Views: 31911

Answers (2)

Tom Marvolo Riddle
Tom Marvolo Riddle

Reputation: 223

↓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
}

Upvotes: 7

Aleksander Blomsk&#248;ld
Aleksander Blomsk&#248;ld

Reputation: 18542

Use Long.toInt():

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

Upvotes: 65

Related Questions