In Kotlin, you can take input from the user using the readLine() function, which reads a line of input as a string from the standard input (usually the keyboard). If you need to read other types of data (e.g., integers or doubles), you will need to convert the input string to the desired type.

Reading Input as a String

To read a line of input as a string:

fun main() {
    println("Please enter your name:")
    val name = readLine()
    println("Hello, $name!")
}

Reading Input as an Integer

To read a line of input and convert it to an integer:

fun main() {
    println("Please enter your age:")
    val age = readLine()?.toIntOrNull()
    if (age != null) {
        println("You are $age years old.")
    } else {
        println("That's not a valid number!")
    }
}

Reading Input as a Double

To read a line of input and convert it to a double:

fun main() {
    println("Please enter your height in meters:")
    val height = readLine()?.toDoubleOrNull()
    if (height != null) {
        println("Your height is $height meters.")
    } else {
        println("That's not a valid number!")
    }
}

Reading Multiple Inputs

If you need to read multiple values from a single line, you can split the input string and then convert the parts to the desired types:

fun main() {
    println("Please enter your name and age separated by a space:")
    val input = readLine()
    val parts = input?.split(" ")

    if (parts != null && parts.size == 2) {
        val name = parts[0]
        val age = parts[1].toIntOrNull()

        if (age != null) {
            println("Name: $name, Age: $age")
        } else {
            println("The second part is not a valid number!")
        }
    } else {
        println("Please provide exactly two values.")
    }
}

Summary

In summary, to take input in Kotlin:

  1. Use readLine() to read a line of input as a string.