If you’re diving into Kotlin, one of the first things you’ll need to get comfortable with is handling input and output (I/O). Whether it’s reading user input from the console or displaying output, understanding I/O is essential for building interactive Kotlin applications. This guide will walk you through the basics, making it as smooth as possible to grasp these concepts.
What is Input and Output in Kotlin?
In programming, input refers to receiving data from the user or another system, while output is the process of presenting data back to the user or to another system. Kotlin makes this process simple and efficient, with built-in methods for both reading input and displaying output.
Output in Kotlin
Let’s start with the easy part—output. Output is simply displaying information to the console or a screen. Kotlin uses the familiar print()
and println()
functions to handle output.
Using print()
and println()
print()
: Prints the content and stays on the same line.println()
: Prints the content and moves the cursor to the next line (adds a line break).
Example:
fun main() {
print("Hello, ") // Output: Hello,
print("World!") // Output: Hello, World!
println("Welcome to Kotlin!") // Output: Hello, World!Welcome to Kotlin!
println("This is a new line.") // Output: This is a new line.
}
As you can see, print()
keeps everything on the same line, while println()
adds a new line after the message. This is helpful for formatting your output.
String Interpolation
One of Kotlin’s powerful features is string interpolation, which allows you to embed variables directly within strings. This makes it easy to output dynamic content.
val name = "Kotlin"
println("Hello, $name!") // Output: Hello, Kotlin!
You can also perform simple expressions inside the string:
val a = 5
val b = 10
println("Sum of $a and $b is ${a + b}") // Output: Sum of 5 and 10 is 15
Input in Kotlin
Now let’s move on to input—the process of receiving data from the user. For reading input from the console, Kotlin uses the readLine()
function.
Reading Input with readLine()
readLine()
reads a line of text entered by the user and returns it as a string. You can then use this input in your program.
Example:
fun main() {
println("Enter your name:")
val name = readLine() // Reads input from the user
println("Hello, $name!")
}
In this example, the user is prompted to enter their name. The readLine()
function captures the input, and the program then greets the user with their name.
Handling Numeric Input
By default, readLine()
returns a string. If you want to handle numeric input (like integers or floats), you’ll need to convert the string to the appropriate type.
Here’s an example of reading an integer input:
fun main() {
println("Enter a number:")
val number = readLine()?.toInt() // Converts the input string to an integer
println("You entered: $number")
}
The toInt()
function converts the string input into an integer. Make sure to use the safe call operator (?.
) to avoid potential NullPointerException
issues if the user provides no input.
Example: Reading Multiple Inputs
You can also read multiple inputs from the user by calling readLine()
multiple times:
fun main() {
println("Enter your first name:")
val firstName = readLine()
println("Enter your last name:")
val lastName = readLine()
println("Your full name is $firstName $lastName")
}
Here, the user is asked to input their first and last names separately, and the program concatenates them to display the full name.
Error Handling for Input
What happens if the user enters invalid input, like trying to input text when a number is expected? This is where exception handling comes into play. Kotlin provides a simple way to handle errors using try-catch
blocks.
Example: Handling Input Errors
fun main() {
println("Enter a number:")
try {
val number = readLine()?.toInt() // Attempts to convert input to an integer
println("You entered: $number")
} catch (e: NumberFormatException) {
println("That's not a valid number.")
}
}
In this example, the program tries to convert the user input into an integer. If the user enters something that can’t be converted, such as a string of text, a NumberFormatException
is thrown, and the program catches the error, displaying a friendly error message instead of crashing.
Input and Output with Files
Apart from reading input from the console, Kotlin also allows you to work with files. You can read data from a file and write output to a file using Kotlin’s built-in libraries.
Writing to a File
Let’s look at how to write output to a file. Kotlin’s standard library provides a method called writeText()
to write content to a file.
import java.io.File
fun main() {
val content = "Hello, Kotlin!"
val file = File("output.txt")
file.writeText(content)
println("File written successfully.")
}
This code creates a new file named output.txt
and writes the string "Hello, Kotlin!"
into it. If the file already exists, it will be overwritten.
Reading from a File
Similarly, you can read input from a file using the readText()
function.
import java.io.File
fun main() {
val file = File("output.txt")
val content = file.readText()
println("File content: $content")
}
In this example, the program reads the content of output.txt
and prints it to the console.
Example Program: Simple Calculator
Now that we’ve covered both input and output, let’s combine everything we’ve learned into a simple calculator program that reads two numbers from the user and performs basic arithmetic operations.
fun main() {
println("Enter first number:")
val num1 = readLine()?.toDoubleOrNull()
println("Enter second number:")
val num2 = readLine()?.toDoubleOrNull()
if (num1 != null && num2 != null) {
println("Choose operation (+, -, *, /):")
val operation = readLine()
val result = when (operation) {
"+" -> num1 + num2
"-" -> num1 - num2
"*" -> num1 * num2
"/" -> num1 / num2
else -> "Invalid operation"
}
println("Result: $result")
} else {
println("Invalid input. Please enter numbers.")
}
}
What Did We Learn?
In this article, we’ve learned how to handle both input and output in Kotlin. We started with the basics of printing to the console using print()
and println()
, then explored reading input from the user using readLine()
. We also looked at error handling, working with files, and even built a simple calculator.
Now that you understand how to work with input and output, you can create interactive programs that take user data and provide useful results.
Ready to move on? In the next article, we’ll dive deeper into working with functions and explore how Kotlin’s functional programming capabilities can make your code more powerful and expressive!