Skip to main content

Kotlin readLine(): getting value from a user

Reading data from user in Kotlin

So far, we have seen how to declare variables and print variables back to user but how do we get input from users?
  • Kotlin has readline() function which returns a line from standard input stream.
  • readLine() returns String which can be converted to other types as required.
Let us look at readLine() function by taking some examples:
// Code:
val msg = readLine()
println("Your msg = $msg")
 
// Output:
Hi
Your msg = Hi
Here, we ask user to enter a message and then promptly display back the same message.

Getting integer or other data types from readLine() method

  • The output returned by readLine() function is String and can be converted to other types.
  • We will learn more about type conversion in our section on data types and conversion.
  • In the meanwhile, here's how you can convert String returned by readLine() to an Integer.
// Code:
println("Enter number 1: ")
    val x = readLine()!!.toInt()
    println("Enter number 2: ")
    val y = readLine()!!.toInt()
    val sum = x + y
    println("Sum = $sum")
 
// Output:
Enter number 1: 
5
Enter number 2: 
3
Sum = 8

  • If you examine the code carefully, you'd find another operator !!, the double exclamation operator.
  • This operator is part of null pointer safely offered by Kotlin.
  • Here, if the output of readLine() is null, instead of calling toInt() on null, the code will fail when met with !! operator.
Note: readLine() may return null if input is redirected to a file and end of file is reached.

Comments