Skip to main content
UInt is a value class in Kotlin that represents a 32-bit unsigned integer. It provides a numeric type strictly constrained to non-negative values, operating within a range of 0 to 4,294,967,295 (23212^{32} - 1). At runtime, UInt wraps a standard primitive Int. While it is designed to avoid object allocation overhead where possible, it is subject to boxing depending on how it is used within the type system.

Instantiation and Syntax

UInt literals are defined by appending the u or U suffix to an integer literal. The compiler can infer the type automatically, or it can be declared explicitly.

Type Conversion

Kotlin enforces strict type safety; implicit conversions between signed Int and unsigned UInt are prohibited. Explicit conversion functions must be invoked.
When converting a negative signed Int to a UInt, the bitwise representation remains identical, resulting in the two’s complement unsigned equivalent.

Arithmetic and Overflow Semantics

UInt supports standard arithmetic and bitwise operators. Operations are executed with unsigned semantics, meaning division and modulo operations evaluate differently than their signed counterparts.
Like signed integers, UInt operations are subject to silent overflow and underflow, wrapping around the 32-bit boundary.

JVM Representation, Boxing, and Unboxing

Because the underlying Java Virtual Machine (JVM) lacks native support for unsigned integer types, Kotlin compiles UInt down to a standard Java primitive int. The Kotlin compiler handles the unsigned arithmetic by substituting the appropriate JVM intrinsics or library functions (e.g., Integer.divideUnsigned). However, because UInt is a value class, it is subject to boxing and unboxing. Boxing occurs when the compiler is forced to instantiate an actual wrapper object on the heap instead of using the underlying primitive int. This introduces memory allocation and performance penalties. UInt is forced to box under the following conditions:
  1. Nullability: When declared as a nullable type (UInt?).
  2. Generics: When used as a generic type argument (e.g., List<UInt>).
  3. Upcasting: When cast to Any or an interface.

Name Mangling

To prevent signature clashes at the bytecode level—since both unboxed Int and UInt erase to int—the Kotlin compiler applies name mangling to functions accepting unboxed UInt parameters.

Arrays

To maintain performance and avoid the boxing overhead associated with generic arrays (like Array<UInt>), Kotlin provides UIntArray. This specialized array type is backed directly by a primitive int[] on the JVM but exposes UInt elements to the Kotlin type system, ensuring no wrapper objects are allocated for its elements.
Tired of Poor Kotlin Skills? Fix That With Deep Grasping!Learn More