Using Kotlin's Standard Input and Output


In Kotlin, you can interact with standard input and output to read user input and display information. This is essential for building console-based applications. In this guide, we'll explore how to use Kotlin's standard input and output for various scenarios.


Reading from Standard Input

You can read user input from the standard input stream using the `readLine()` function. Here's a basic example:

val userInput = readLine()
println("You entered: $userInput")

This code reads a line of text from the user and prints it back.


Working with Numbers from Input

When you need to read numbers, you can parse the input as follows:

print("Enter an integer: ")
val number = readLine()?.toIntOrNull()
if (number != null) {
println("You entered: $number")
} else {
println("Invalid input. Please enter a valid integer.")
}

In this example, we read a line of text from the user, attempt to convert it to an integer, and handle invalid input gracefully.


Printing to Standard Output

To display information to the user, use the `println()` function:

println("Hello, Kotlin!")

You can also use `print()` if you don't want a newline character at the end of the output.


Formatted Output

Kotlin supports string interpolation for formatted output:

val name = "Alice"
val age = 30
println("Name: $name, Age: $age")

Conclusion

Using Kotlin's standard input and output functions allows you to build interactive console applications, read user input, and display information. Whether you're creating command-line tools or interactive games, these basic I/O operations are fundamental to the development of many applications.


Happy coding!