Kotlin readLine() Function Tutorial

In this section, we will learn what the readLine() function is and how to use it in Kotlin.

What is readLine() Function in Kotlin? (Reading in User Inputs)

The readLine() function is a way of reading an input from the standard terminal.

Simply call this function and it will cause the program to pause in order to take an input from a user.

This input is in the form of a string value and can be then assigned to a variable.

Kotlin readLine() Function Syntax:

var variable_name = readLine()

As you can see, when calling the readLine() function, its value can be assigned to a variable.

Note: this function will drop the newline character that will be added to the string value as a result of hitting the enter key on the keyboard.

Example: getting user inputs using readLine() Function

fun main(){
    println("Please enter your name: ")
    var name = readLine() 

    println("Hello ${name} :)")
}

Output:

Please enter your name:

Omid

Hello Omid 🙂

How Does readLine() Function Work in Kotlin?

As you can see, we’ve called the readLine() function in order to take a name from users and then assigned the result to the name variable. We then sent this value to the output stream.

Note: if you’re asking a user to enter an integer number, for example, you need to cast the returned value of the readLine() function into an integer type because the return data type of this function is String.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies