Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Conversion to Other Types

Command line arguments are provided to a program as strings, and the readln() function returns a string. But what if you are expecting the input to be a number?

In such cases, you can use one of the many numeric conversion functions associated with the String class. For example, to parse a string into an integer value, you can invoke toInt() or toLong(). To parse the string into a floating-point value you can use toFloat() or toDouble().

Here’s an example of how you could input a user’s age in a Kotlin program. The equivalent code in C and Python is provided for comparison:

print("Please enter your age: ")
val age = readln().toInt()
int age;
printf("Please enter your age: ");
scanf("%d", &age);
age = int(input("Please enter your age: "))

Notice the use of call chaining in this Kotlin example. The readln() function returns a String object, upon which we immediately invoke toInt().

You’ll see this pattern frequently in Kotlin, Java, and other object-oriented languages. The benefit here is that it avoids the need for an additional variable just to hold the value returned by readln().

In parallel with toInt(), toDouble(), etc, Kotlin provides extension functions named toIntOrNull(), toDoubleOrNull(), etc. These deal with invalid conversions in a different way. There is also a function named readlnOrNull(), whose behaviour differs from readln() slightly. We will discuss these functions later, when we cover null safety.

Task 3.3

  1. Edit the file Conversion.kt, in the tasks/task3_3 subdirectory of your repository.

    In this file, create a small program containing the two lines of Kotlin code shown above. Add a third line that prints the age entered by the user.

  2. To see how valid input is handled, compile the program in the usual way, then run it and enter your own age.

  3. Run the program a few more times, with the following as inputs:

    19.5
    nineteen
    3147203180
    

    What do you observe? Do you understand why the third example fails?

    Hint

    What is the type of variable age?

    Are there any restrictions associated with this type?

  4. Optional: would you see different behaviour in C when parsing these strings to an integer using the scanf() or atoi() functions?

    Write a small C program to see whether you are right.