Type Conversion

No Automatic Widening

Java converts int to long for you. Kotlin does not; you must convert explicitly. This avoids hidden bugs.

val i: Int = 100
val l: Long = i          // ERROR: Type mismatch
val l2: Long = i.toLong() // OK

Conversion Functions

Example

Every number type has toInt(), toLong(), toDouble(), toFloat(), toString()... Converting a decimal to an integer cuts off the fraction.

import kotlin.math.roundToInt

fun main() {
    val rating = 4.7
    println(rating.toInt())          // 4 (truncated)
    println(rating.roundToInt())     // 5 (rounded)

    val qty = 3
    println(qty.toDouble())
    println(qty.toString() + " items")

    val big = 3_000_000_000L
    println(big.toInt())             // does not fit: garbage value
}

Output

4
5
3.0
3 items
-1294967296

String to Number

Example

Text from a form or an API must be converted. toInt() throws if the text is not a number; toIntOrNull() returns null instead, which is safer.

fun main() {
    println("42".toInt() + 1)
    println("99.5".toDouble())
    println("12abc".toIntOrNull())
    println("".toIntOrNull())
    val pinCode = "500081".toIntOrNull() ?: 0
    println(pinCode)
}

Output

43
99.5
null
null
500081

Bad Input

With toInt(), bad input crashes the program with NumberFormatException:

fun main() {
    val ageText = "twenty"
    println("Converting...")
    val age = ageText.toInt()
    println(age)
}

Output

Converting...
Exception: java.lang.NumberFormatException: For input string: "twenty"