So far, in all the programs, we were supplying the values of the variables in our code. But that’s not what we want always. There should be some way to receive input values from the user. Kotlin provides a simple way to do this.
How to read user input values?
We can use the function readLine() to get user inputs in Kotlin. The usage is:
var varname = readLine()
The readLine() function is for getting Kotlin user input. It reads input from the keyboard and returns it to the callee as a string. Always keep this in mind, the value we obtain from readLine() function is a string. For doing arithmetic operations, we need numerical types like Int or Float. So, what do we do? We will convert this string value to the numerical types.
var varname = readLine().toInt() //Error
It won’t compile. It has an error, saying Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String? Don’t worry about it too much. There’s something called null safety in Kotlin. We’ll cover it shortly. This error is because the compiler is making sure the value returning from the readLine() is not null. That is, the readLine() function can return a null value. When we try to convert a null value to another type, the program crashes. By throwing a compiler error, the compiler is forcing us to take care of the situation while writing the program. Run time errors are harder to debug than compile time errors.
Solution to the error
We can get around this problem by adding a safe call operator or a null assertion to the statement. So, the code would be:
var varname = readLine()?.toInt()
var varname = readLine()!!.toInt()
The first one is called a safe call. The toInt() function will be called only when the value returned is not null.
The second one is a non-null assertion. We’re telling the compiler that we are 100% sure that the value returned from readLine() won’t be a null value.
println("Enter a value : ")
val inval = readLine()!!.toFloat()
println("Enter a value : ")
val inval = readLine()!!.toBoolean()
- Rewrite all the exercise programs using loops to accept user inputs.
- Write a calculator program to display a menu. Accept the choice of operation from the user. Then it should ask for two values calculate and display the result. After displaying the result it should come back to the menu. There should be an entry in the menu to exit. Otherwise the program returns back to the menu after the operation (use do..while loop for returning back)
So, this is all about reading user inputs in Kotlin. Drop a comment to let me know what you think about this post.
Happy coding 🙂
« Back to the index of Kotlin tutorial
I’m Shiju P John, a tech enthusiast. I study for CS engineering at present. Writing on this blog is my hobby and passion.