How to use Scanner class in Kotlin to read user inputs

Introduction :

Scanner class is actually a Java class. It is defined in java.util package. If you are from Java background, you must be aware of this class and how to use it. In Kotlin also, we can create one Scanner variable and use it to read user inputs.

In this post, I will show you how to use Scanner class in Kotlin with one simple example.

Read user input using Scanner in Kotlin :

Let’s write one program to read the user input string using Scanner :

import java.util.Scanner

fun main() {
    val sc = Scanner(System.`in`)
    println("Enter a line : ")
    val userInput = sc.nextLine()

As you can see here, we are creating one Scanner object and reading the user input line using nextLine method. Scanner provides a lot of different methods to read user input values.

Sample Output :

Enter a line : 
Hello World !!
Hello World !!

Kotlin scanner example

All methods are define in class and these are same as we use in a Java program.