How to take input from user in Kotlin :

In this tutorial, we will learn how to take user input in Kotlin with different examples.
Reading user input in Kotlin is easy. Kotlin provides one inbuilt function to make this task easy for us.
readLine() function allow us to read the input that is entered by the user. This function actually read the input as a string. We can convert it to a different datatype if we want.
Alternatively, we can also use Scanner class to read the content of user input.

Read user input string using readLine() :

Let’s try to create one simple project first. The user will enter one line, our program will read it using readLine() and then it will print out the result :

fun main(args: Array) {
    println("Enter a string :")
    val userInputString = readLine()

    println("You have entered : $userInputString")

Sample output :

Enter a string :
hello world
You have entered : hello world

Enter a string :
You have entered : 1234567

kotlin user input

Read content using readLine() and convert it :

As we have explained earlier that readLine() actually read the contents as a string but we can also convert them to any other formats.
For example, if we want to convert a string integer to an integer value, we can do it by using Integer.valueOf() or toInt() method.

fun main(args: Array) {
    println("Enter a integer :")
    val userInputInt = Integer.valueOf(readLine())

    println("You have entered : $userInputInt")

    println("Enter another integer : ")
    val userInputInt2 = readLine()!!.toInt()

    println("Using toInt() : $userInputInt2")

Sample Output :

Enter a integer :
You have entered : 12
Enter another integer :
Using toInt() : 23

kotlin user input

Similarly, we can get convert other data types in kotlin.

Using Scanner class :

We can also use java.util.Scanner class to read user contents in Kotlin. We can use nextInt(),nextFloat(),nextLong(),nextBoolean() and nextDouble() methods to read int,float,long,boolean and double value from a user input.

import java.util.Scanner

fun main(args: Array) {
    val scanner = Scanner(System.`in`)

    println("Enter a integer :")
    val intNum = scanner.nextInt()

    println("Enter a float : ")
    val floatNum = scanner.nextFloat()

    println("Entered integer : $intNum")
    println("Entered float : $floatNum")

Sample Output :

Enter a integer :
Enter a float :
Entered integer : 12
Entered float : 34.54

kotlin read user input

Conclusion :

As you can see that we have different ways to read the contents from a user in Kotlin. Try to run the examples above and drop one comment below if you have any queries.

Categories: kotlin

Leave a Reply

Your email address will not be published. Required fields are marked *