Integer
Represents an integer.
Use this type for preventing overflow when performing arithmetic operations with integers, and for consistent behavior across all platforms when dividing an integer by zero.
Motivations
Motivations
Integer overflow
Problem: Adding, subtracting or multiplying Kotlin integer types (Byte, Short, Int and Long) can lead to an overflow, which produces unexpected behavior.
val x = 9223372036854775807
val y = 10
check(x + y == -9223372036854775799) // instead of 9223372036854775817
check(-x - y == 9223372036854775799) // instead of -9223372036854775817
check(x * y == -10L) // instead of 92233720368547758070Solution: The Integer type can add, subtract or multiply integers without producing an overflow.
val x: Integer = Integer.from(9223372036854775807)
val y: Integer = Integer.from(10)
check(x + y == Integer.fromDecimal("9223372036854775817"))
check(-x - y == Integer.fromDecimal("-9223372036854775817"))
check(x * y == Integer.fromDecimal("92233720368547758070"))Division by zero
Problem: Performing division and remainder operations by zero on Kotlin integer types have different behavior per platform: throw an ArithmeticException on JVM and Native platforms, and return 0 on JS platform.
// JVM and Native platforms
val quotient: Result<Int> = kotlin.runCatching { 12 / 0 }
val remainder: Result<Int> = kotlin.runCatching { 12 % 0 }
check(quotient.exceptionOrNull() is ArithmeticException)
check(remainder.exceptionOrNull() is ArithmeticException)// JS platform
check(12 / 0 == 0)
check(12 % 0 == 0)Solution: Division and remainder operations by zero on Integer type throw an ArithmeticException on all platforms.
// Common code
val x: Integer = Integer.from(12)
val y: Integer = Integer.from(0)
val quotient: Result<Integer> = kotlin.runCatching { x / y }
val remainder: Result<Integer> = kotlin.runCatching { x % y }
check(quotient.exceptionOrNull() is ArithmeticException)
check(remainder.exceptionOrNull() is ArithmeticException)Key features
Key features
Creations: Create from Long number (from) or decimal string (fromDecimal).
Comparisons: Compare integers using structural equality (
x == y,x != y) and ordering (x < y,x <= y,x > y,x >= y) operators.Arithmetic operations: Add (
x + y), subtract (x - y), multiply (x * y), divide (x / y), compute remainders (x % y), and negate (-x) integers without overflow.Conversions: Convert to its decimal string representation.