Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: January 3, 2023
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.
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.
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.
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.
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.