1. Introduction

In Kotlin, it’s possible to convert a Long value to an Int value. However, there are some subtle differences. Let’s take a look.

2. The toInt() Helper Function

In Kotlin, the Long class has a useful helper function called toInt(). Using this function, we can convert a Long value to an Int value:

val longValue = 100L
val intValue = longValue.toInt()

Here, we are converting a Long value to an Int value using the toInt function. However, there are limitations to this conversion.

3. The Truncation Problem

As we know, Long is a ‘bigger’ type than Int. This means if we try to convert a Long value that’s smaller than Int.MIN_VALUE or larger than Int.MAX_VALUE, we might get truncated results.

Specifically, the toInt() function returns an Int value represented by the least significant 32 bits of the given Long value for such a conversion.

4. Handling Truncation With an Extension Function

In some cases, the default truncation behavior of the toInt function may not be desirable. Interestingly, we can write our own extension functions to achieve the desired behavior. For instance:

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

In this extension function, we return the expected Int value if the Long value is larger than Int.MIN_VALUE and smaller than Int.MAX_VALUE. However, if the Long value is outside that range, we return null instead.

This allows the calling code to identify and handle “narrowing” conversions relatively easier than toInt‘s default truncation behavior.

5. Conclusion

An easy way to convert a Long value to an Int value is to use the toInt() helper function. Additionally, to achieve custom truncation behavior, we can also write our own extension functions.

As always, the code samples are available over on GitHub.