How to Take Input in Kotlin: Simple Guide with Examples
In Kotlin, you can take input from the user using the
readLine() function, which reads a line of text from the standard input as a String?. To convert this input to other types like Int, use safe calls and conversion functions like toInt().Syntax
The basic syntax to take input in Kotlin is using the readLine() function. It reads a line of text from the user and returns it as a nullable String?. You often convert this string to other types depending on your needs.
val input = readLine(): Reads input as a nullable string.input?.toInt(): Converts the input string to an integer safely.
kotlin
val input: String? = readLine() val number: Int? = input?.toInt()
Example
This example shows how to ask the user for their age, read it as input, convert it to an integer, and print a message using that input.
kotlin
fun main() {
print("Enter your age: ")
val input = readLine()
val age = input?.toIntOrNull()
if (age != null) {
println("You are $age years old.")
} else {
println("Invalid input. Please enter a number.")
}
}Output
Enter your age: 25
You are 25 years old.
Common Pitfalls
One common mistake is not handling the nullable nature of readLine() and the possibility of invalid input when converting to numbers. This can cause your program to crash with exceptions.
Always use safe calls like ?.toIntOrNull() and check for null before using the input.
kotlin
fun main() {
// Wrong way: may crash if input is not a number
// val age = readLine()!!.toInt()
// Right way: safely convert and check
val age = readLine()?.toIntOrNull()
if (age == null) {
println("Please enter a valid number.")
} else {
println("Your age is $age.")
}
}Quick Reference
| Function | Description |
|---|---|
| readLine() | Reads a line of input as a nullable String |
| toInt() | Converts String to Int, throws exception if invalid |
| toIntOrNull() | Converts String to Int or returns null if invalid |
| ?. | Safe call operator to handle nullable values |
Key Takeaways
Use readLine() to read user input as a nullable String in Kotlin.
Convert input safely using toIntOrNull() to avoid crashes on invalid input.
Always check for null before using converted input values.
Print prompts before reading input to guide the user.
Handle input errors gracefully to improve user experience.