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.
| Type | Bits |
|---|---|
| Byte | 8 |
| Short | 16 |
| Int | 32 |
| Long | 32 |
| Float | 32 |
| Double | 64 |
💡
ShortandBytearen’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
| Type | Bits |
|---|---|
| UByte | 8 |
| UShort | 16 |
| UInt | 32 |
| ULong | 64 |
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 easierWorking 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