Menu
Coddy logo textTech

Type Conversion

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 38 of 93.

Since readLine() returns a nullable string (null at end of input), you'll need to convert that input when you want to work with numbers. Kotlin provides conversion functions to transform strings into other types.

To convert a string to an integer, use toInt():

fun main() {
    val input = readLine()!!
    val number = input.toInt()
    println(number + 10)
}

If the user enters "5", the program converts it to the integer 5, then adds 10 to get 15. Without conversion, "5" + 10 concatenates text and produces "510". Converting first gives numeric addition.

For decimal numbers, use toDouble():

fun main() {
    val price = readLine()!!.toDouble()
    println("With tax: ${price * 1.1}")
}

You can chain the conversion directly after readLine()!! for cleaner code. Other useful conversions include toLong() for large integers and toBoolean() for boolean values.

These conversions assume the input is valid. If someone enters "hello" when you expect a number, the program will crash. You'll learn to handle such errors later in the course.

challenge icon

Challenge

Easy

Write a function calculateFutureAge that takes currentAge and yearsToAdd as strings and returns the future age as an integer.

Convert both string parameters to integers, add them together, and return the result.

Parameters:

  • currentAge (String): The current age as a string (e.g., "25")
  • yearsToAdd (String): The number of years to add as a string (e.g., "10")

Returns: The sum of both values as an integer (Int)

Try it yourself

fun calculateFutureAge(currentAge: String, yearsToAdd: String): Int {
    // Write code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground