← 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.
Syntax
kotlin
val asDouble = intValue.toDouble()      // toInt(), toLong(), toFloat()
val number = stringValue.toInt()        // throws if not a valid number
val safe = stringValue.toIntOrNull()    // null if invalid

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
// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `wholeNumber` (an Int), set to `10`
    val wholeNumber: Int = 10
    // Declare a read-only variable `decimalNumber` (a Double), set to `wholeNumber.toDouble()`
    val decimalNumber: Double = wholeNumber.toDouble()
    // Print "Int: $wholeNumber, Double: $decimalNumber" to the console, with a trailing newline
    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
// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `price` (a Double), set to `19.99`
    val price: Double = 19.99
    // Declare a read-only variable `roundedDown` (an Int), set to `price.toInt()`
    val roundedDown: Int = price.toInt()
    // Print "Price: $price, as Int: $roundedDown" to the console, with a trailing newline
    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
// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `text`, set to `"42"`
    val text = "42"
    // Declare a read-only variable `number`, set to `text.toInt()`
    val number = text.toInt()
    // Print "Parsed number: ${number + 8}" to the console, with a trailing newline
    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
// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `goodInput`, set to `"123"`
    val goodInput = "123"
    // Declare a read-only variable `badInput`, set to `"abc"`
    val badInput = "abc"
    // Print "Good: ${goodInput.toIntOrNull()}" to the console, with a trailing newline
    println("Good: ${goodInput.toIntOrNull()}")
    // Print "Bad: ${badInput.toIntOrNull()}" to the console, with a trailing newline
    println("Bad: ${badInput.toIntOrNull()}")
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
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.