toLong
Returns the Long representation of this integer, or throws an ArithmeticException if this integer is out of range for Long.
This conversion validates the Long range directly against the platform-specific backing representation before extracting the numeric value of this integer. It deliberately avoids a textual round-trip such as this.toString().toLong(), which would allocate and parse an intermediate String on every call.
Calling from Kotlin
Here's an example of calling this function from Kotlin code:
val x: Integer = Integer.fromLong(42)
val result: Long = x.toLong()
check(result == 42L)
val outOfRange: Integer =
Integer.fromLong(Long.MAX_VALUE) + Integer.fromLong(1)
val exception: Throwable? = runCatching(outOfRange::toLong)
.exceptionOrNull()
check(exception is ArithmeticException)Content copied to clipboard
Calling from Java
Here's an example of calling this function from Java code:
final Integer x = Integer.fromLong(42);
final long result = x.toLong();
if (result != 42L) throw new IllegalStateException("Check failed.");
final Integer outOfRange =
Integer.fromLong(Long.MAX_VALUE).plus(Integer.fromLong(1));
try {
outOfRange.toLong();
throw new IllegalStateException("Check failed.");
} catch (ArithmeticException ignored) {
}Content copied to clipboard
See the toLongOrNull function for returning null instead of throwing an exception when this integer is out of range for Long.
Since
5.2.0