← Back to Kotlin Course | Chapter 2: Variables & Types | Lesson 5 of 7

Type Conversion

Type conversion is turning one kind of value, like a number, into another kind, like text, so different pieces of data can work together.

No Implicit Widening

Unlike some languages, Kotlin never automatically converts an Int to a Double even though a Double can represent every Int value. Assigning across numeric types always requires an explicit conversion function.

Example: No Implicit Widening

markup
fun main() {
    val wholeNumber: Int = 10
    val decimalNumber: Double = wholeNumber.toDouble()
    println("Int: $wholeNumber, Double: $decimalNumber")
}

Converting Between Numeric Types

Functions like toInt(), toLong(), toFloat(), and toDouble() convert a number from one numeric type to another, truncating or widening as appropriate.

Note: Converting a Double to an Int truncates the decimal part rather than rounding.

Example: Converting Between Numeric Types

markup
fun main() {
    val price: Double = 19.99
    val roundedDown: Int = price.toInt()
    println("Price: $price, as Int: $roundedDown")
}

Converting Strings to Numbers

toInt(), toDouble(), and similar functions parse a String into a number, but they throw a NumberFormatException if the text is not a valid number.

Example: Converting Strings to Numbers

markup
fun main() {
    val text = "42"
    val number = text.toInt()
    println("Parsed number: ${number + 8}")
}

Safe Conversion with OrNull

toIntOrNull(), toDoubleOrNull(), and similar functions return null instead of throwing when the string cannot be parsed, which is safer for handling untrusted input.

Example: Safe Conversion with OrNull

markup
fun main() {
    val goodInput = "123"
    val badInput = "abc"
    println("Good: ${goodInput.toIntOrNull()}")
    println("Bad: ${badInput.toIntOrNull()}")
}
Common Mistakes
  1. Expecting implicit widening conversions like in Java/C, such as assigning an Int directly to a Double variable; Kotlin requires an explicit toDouble() call.
  2. Using as for numeric conversions instead of the proper toInt()/toDouble() functions, which is meant for type casting, not conversion.
  3. Calling toInt() on a non-numeric string and not handling the NumberFormatException that results.
Chapter Summary
  • Kotlin never performs implicit numeric conversions; every conversion between types like Int and Double must be explicit.
  • Conversion functions like toInt(), toDouble(), toLong(), and toString() convert between numeric types and strings.
  • Converting a non-numeric string with toInt() throws a NumberFormatException at runtime.
  • toIntOrNull() and similar OrNull variants return null instead of throwing when conversion fails.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.