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

Console Input

Kotlin’s standard library provides the function readln() to read a line of input from the console. This line of input is returned as a String object.

Here’s an example, with the equivalent C and Python code provided for comparison:

print("Enter your name: ")
val name = readln()
char name[80];
printf("Enter your name: ");
fgets(name, sizeof name, stdin);
name = input("Enter your name: ")

You can see that Python’s approach is the most concise and C’s the most verbose, with Kotlin somewhere in between.

Task 3.2

  1. In the tasks/task3_2 subdirectory of your repository, create a small Kotlin program containing the two lines shown above.

    Add a third line that prints the length of the string supplied by the user. This is available to you as the length property of the string variable, i.e., name.length.

  2. Compile the program, then run it a few times, trying various lengths of input, including no input at all (just press the Enter key for this, without typing anything else).

  3. Now run the program and press Ctrl+D instead of entering anything. What happens?