Algus

numbers

Numeric Types

Kotlin numeric types come in two flavors: signed and unsigned. Numeric types primarly differ in the number of bits they are allocated in memory and their minimum/maximum value.

Kotlin uses the same rule as Java for its numeric types.

TypeBits
Byte8
Short16
Int32
Long32
Float32
Double64

💡 Short and Byte aren’t commonly used for representing conventional number, they are used for specialized cases and to support interoperability, typically with legacy programs.

If your application needs to store a mission-critical decimal value where rounding and loss of precision are unacceptable, neither Float nor Decimal is the solution.

Unsigned numbers

TypeBits
UByte8
UShort16
UInt32
ULong64

Using an unsigned numeric type takes a bit more effort than a signed number.

var level:UInt = 5.toUInt()
var positiveNumber = 5u // suffixing with `u` is easier

Working with unsigned numeric types has some extra effort as to make operations, it should use the same types and Kotlin won’t make the conversion automatically.

Something interesting to note here is that unsigned numbers aren’t bulletproof.

var positiveNumber = (-1).toUInt() // 4294967295
// ^Integer underflow