Type conversion

suggest change

Kotlin has no implicit numeric conversions. An Int is never silently widened to a Long or Double. Every conversion is an explicit function call such as toLong() or toDouble(). This prevents a class of subtle bugs common in Java and C, but it means you need to know which conversion functions exist and how they behave at the edges.

No implicit widening

Code that compiles in Java is rejected by Kotlin:

val i: Int = 1
val l: Long = i        // error: initializer type mismatch: expected 'Long', actual 'Int'
println(i == 1L)       // error: operator '==' cannot be applied to 'Int' and 'Long'

Convert explicitly:

val i: Int = 42
val l: Long = i.toLong()
val d: Double = i.toDouble()
println("$l $d") // 42 42.0

Arithmetic operators are overloaded for mixed types, so 1 + 2L is a Long and 5 / 2.0 is a Double. Assignment and comparison with == are where explicit conversion is required.

Literals adapt to the expected type when the value fits, so val b: Byte = 10 and val l: Long = 10 both compile.

Number to number

Every numeric type (Byte, Short, Int, Long, Float, Double) has toByte(), toShort(), toInt(), toLong(), toFloat() and toDouble(). The behaviour depends on the direction.

Integer narrowing wraps around

Converting to a smaller integer type keeps the low-order bits. No exception is thrown:

println(3_000_000_000L.toInt()) // -1294967296
println(300.toByte())           // 44
println(70000.toShort())        // 4464
println(0xFF.toByte())          // -1

If you need a checked conversion, use the java.lang.Math helpers on JVM:

Math.toIntExact(3_000_000_000L) // throws ArithmeticException: integer overflow

Floating point to integer truncates and saturates

toInt() and toLong() on Double/Float round toward zero. Out-of-range values clamp to the min/max of the target type and NaN becomes 0:

println(3.99.toInt())                      // 3
println((-3.99).toInt())                   // -3
println(1e20.toInt())                      // 2147483647
println(Double.NEGATIVE_INFINITY.toLong()) // -9223372036854775808
println(Double.NaN.toInt())                // 0

To round instead of truncate, use kotlin.math:

import kotlin.math.roundToInt
import kotlin.math.round

println(2.5.roundToInt())     // 3 (ties round up, toward positive infinity)
println((-2.5).roundToInt())  // -2
println(round(2.5))           // 2.0 (ties round to even)

roundToInt() throws IllegalArgumentException for NaN.

Deprecated: Double.toShort() and Double.toByte()

Double.toShort(), Double.toByte() and the Float equivalents are deprecated (an error in current Kotlin) because the result was unclear. Convert to Int first and then narrow:

val d = 3.7
// d.toShort()          // error: Unclear conversion
val s: Short = d.toInt().toShort() // 3

Integer to floating point can lose precision

Float has 24 bits of mantissa and Double has 53, so large integers may not survive a round trip:

println(16_777_217.toFloat().toInt()) // 16777216
println(Int.MAX_VALUE.toFloat())      // 2.1474836E9

String to number

The standard library adds parsing extensions to String:

val a = "42".toInt()          // 42
val b = "3.14".toDouble()     // 3.14
val c = "1e3".toDouble()      // 1000.0
val d = "+7".toInt()          // 7
val big = "9000000000".toLong()

Invalid input throws NumberFormatException. That includes surrounding whitespace and values out of range for the type. For user input, prefer the ...OrNull variants, which return null instead:

println("abc".toIntOrNull())        // null
println(" 42".toIntOrNull())        // null (whitespace is not trimmed)
println(" 42".trim().toIntOrNull()) // 42
println("2147483648".toIntOrNull()) // null (overflows Int)

val port = System.getenv("PORT")?.toIntOrNull() ?: 8080

Combined with mapNotNull this filters out bad values:

val nums = listOf("1", "x", "3").mapNotNull { it.toIntOrNull() } // [1, 3]

Radix

Integer parsing and formatting take an optional radix (2 to 36):

println("ff".toInt(16))                     // 255
println("1010".toInt(2))                    // 10
println(255.toString(16))                   // ff
println(255.toString(2).padStart(16, '0'))  // 0000000011111111

BigDecimal and BigInteger

val price = "19.99".toBigDecimal()
val huge = "123456789012345678901234567890".toBigInteger()
println("0.1".toBigDecimal() + "0.2".toBigDecimal()) // 0.3
println(price.toInt())                               // 19 (truncates)

Double.toBigDecimal() goes through Double.toString(), so 0.1.toBigDecimal() is 0.1. Using the Java constructor BigDecimal(0.1) instead gives the exact binary value 0.1000000000000000055511151231257827.... Parsing from a String is the clearest option.

Number to string

toString() and string templates give the default representation:

println(42.toString())  // 42
println("${1.0}")       // 1.0
println(1e7)            // 1.0E7
println(1e-4)           // 1.0E-4

Use String.format for control over decimals, padding and grouping:

println("%.2f".format(3.14159))   // 3.14
println("%05d".format(42))        // 00042
println("%,d".format(1234567))    // 1,234,567
println("%x".format(255))         // ff
println("%e".format(12345.678))   // 1.234568e+04

format uses the default locale, so on a German system %.2f prints 3,14. When the output is machine-readable (JSON, CSV, file names), pass a locale: String.format(Locale.ROOT, "%.2f", x).

For BigDecimal, toPlainString() avoids scientific notation:

println("1E+3".toBigDecimal().toPlainString())                 // 1000
println("01.50".toBigDecimal().stripTrailingZeros().toPlainString()) // 1.5

Char and Int

Char is not a number in Kotlin. Use the code property and the Char(code) constructor:

println('A'.code)   // 65
println(Char(66))   // B

Char.toInt() and Number.toChar() (except Int.toChar()) are deprecated in favour of these.

To get the numeric value of a digit character, use digitToInt(), not code:

println('7'.digitToInt())       // 7
println('7'.code)               // 55 (the code point, usually not what you want)
println('f'.digitToInt(16))     // 15
println('x'.digitToIntOrNull()) // null
println(7.digitToChar())        // 7
println(11.digitToChar(16))     // B

String to Boolean

println("true".toBoolean())  // true
println("TRUE".toBoolean())  // true (case-insensitive)
println("yes".toBoolean())   // false (anything else is false)

toBoolean() never fails, which can hide typos in configuration. toBooleanStrict() accepts only "true" and "false" (case-sensitive) and throws otherwise; toBooleanStrictOrNull() returns null:

println("True".toBooleanStrictOrNull()) // null
"yes".toBooleanStrict() // IllegalArgumentException: The string doesn't represent a boolean value: yes

Unsigned types

UByte, UShort, UInt and ULong convert with toUInt(), toInt() and friends. Converting between signed and unsigned reinterprets the bits:

val u: UInt = 42u
println(u.toInt())             // 42
println((-1).toUInt())         // 4294967295
println(UInt.MAX_VALUE.toLong()) // 4294967295
println("4294967295".toUInt()) // 4294967295
println((-1).toByte().toUByte()) // 255

A common use is reading bytes as values in 0..255. Without unsigned types, mask with and 0xFF:

val b: Byte = 0xFF.toByte()
println(b.toInt())          // -1
println(b.toInt() and 0xFF) // 255
println(b.toUByte())        // 255

Collection conversions

val list = listOf(3, 1, 2, 3)

val set: Set<Int> = list.toSet()              // [3, 1, 2]
val mutable = list.toMutableList()
val ints: IntArray = list.toIntArray()        // primitive int[]
val boxed: Array<Int> = list.toTypedArray()   // Integer[]
val back: List<String> = arrayOf("a", "b").toList()

val map = listOf("a" to 1, "b" to 2).toMap()  // {a=1, b=2}
val pairs = map.toList()                      // [(a, 1), (b, 2)]

val chars = "abc".toList()                    // [a, b, c]
val s = charArrayOf('o', 'k').concatToString() // ok

val strings = list.map { it.toString() }      // element-wise conversion

toIntArray(), toLongArray() etc. produce primitive arrays, which is what Java methods taking int[] expect. toTypedArray() produces boxed arrays (Integer[]), and is what you need for vararg spreading: String.format(fmt, *args.toTypedArray()).

The to... functions always create a copy. To get a read-only view without copying, just use the list as a List; to share a mutable list as read-only, upcast it.

Casting is not conversion

as, as? and is check or assert the runtime type of an object. They never change a value:

val any: Any = 42
println(any is Int)        // true
println((any as Int) + 1)  // 43
println(any as? String)    // null
any as Long                // ClassCastException: Integer cannot be cast to Long

An Int boxed as Any is not a Long, even though the value fits. To convert, go through Number:

val n: Number = 3.9
println(n.toInt())  // 3
println(n.toLong()) // 3

After an is check the compiler smart casts the variable, so a separate as is unnecessary:

fun describe(x: Any): String = when (x) {
    is Int -> "int, doubled: ${x * 2}"
    is String -> "string of length ${x.length}"
    else -> "unknown"
}

Generic type arguments are erased at runtime, so as? List<String> only checks that the value is a List and produces an unchecked-cast warning. listOf(1, 2) as? List<String> succeeds and fails later when an element is used as a String. Use filterIsInstance<String>() to get a correctly typed list.

Java interop notes

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents