In many applications, user interaction is a very important part, and the most basic way of doing that is reading input entered by the user and giving output based on it. In this recipe, we will understand different ways of reading input and also provide output in the console.
Reading console input in Kotlin
Getting ready
You need to install a preferred development environment that compiles and runs Kotlin. You can also use the command line to compile and run your Kotlin code, for which you need Kotlin compiler installed along with JDK.
How to do it...
Let's go through the following steps by which we can read console input in Kotlin:
- We will start simple and move to more advanced logic as we move forward. First, let's start with simply printing a line as output in the console:
println("Just a line")
- Now we will try to take String input from the console and output it again:
println("Input your first name")
var first_name = readLine()
println("Your first name: $first_name")
- Okay, how about we repeat the process with Int:
println("Hi $first_name, let us have a quick math test. Enter two numbers separated by space.")
val (a, b) = readLine()!!.split(' ').map(String::toInt)
println("$a + $b = ${a+b}")
- Now, let's try a complicated code and then start with the explanations:
fun main(args: Array<String>) {
println("Input your first name")
var first_name = readLine()
println("Input your last name")
var last_name = readLine()
println("Hi $first_name $last_name, let us have a quick math test. Enter two numbers separated by space.")
val (a, b) = readLine()!!.split(' ').map(String::toInt)
println("what is $a + $b ?")
println("Your answer is ${if (readLine()!!.toInt() == (a+b)) "correct" else "incorrect"}")
println("Correct answer = ${a+b}")
println("what is $a * $b ?")
println("Your answer is ${if (readLine()!!.toInt() == (a*b)) "correct" else "incorrect"}")
println("Correct answer = ${a*b}")
println("Thanks for participating :)")
}
Here's a screenshot of compiling and running the preceding code:
How it works...
Let's try to understand the methods by which we were able to read input in Kotlin.
Behind the scenes, Kotlin.io uses java.io for the input-output. So println is basically System.out.println, but with additional power by Kotlin to use String templates and inline functions, which makes writing extremely simple and concise.
This is a part of the actual code from Kotlin stdlib used for Console IO:
/** Prints the given message and newline to the standard output stream. */
@kotlin.internal.InlineOnly
public inline fun println(message: Any?) {
System.out.println(message)
}