Skip to content
AgileLogics
4 min read

Type Conversion

Prerequisites: Working with nullable values

Kotlin never converts between types automatically — you call a conversion function explicitly.

Between number types

fun main() {
    val whole = 7
    val decimal = 2.9

    println(whole.toDouble())
    println(decimal.toInt())
    println(whole.toLong())
    println(65.toChar())
    println('A'.code)
}
7.0
2
7
A
65

toInt() on a Double truncates — it drops the decimals.

Numbers to strings

fun main() {
    val score = 42
    println(score.toString() + "!")
    println("$score!")
}
42!
42!

Strings to numbers

There are two versions of each conversion:

  • toInt(), toDouble() — throw a NumberFormatException if the text isn't a valid number.
  • toIntOrNull(), toDoubleOrNull() — return null instead.
fun main() {
    val inputs = listOf("42", "3.5", "abc", " 7")

    for (input in inputs) {
        val number = input.toIntOrNull()
        if (number != null) {
            println("'$input' → $number")
        } else {
            println("'$input' → not a whole number")
        }
    }
}
'42' → 42
'3.5' → not a whole number
'abc' → not a whole number
' 7' → not a whole number

Conversion is strict — even a leading space fails. Call trim() on user input first.

Common mistakes

  • Using toInt() on user input and crashing on the first typo. Use toIntOrNull() and handle null.