Chapter 5: Input & Output Basics
Input & Output Basics in Kotlin — this is the chapter where your programs stop being silent and start talking to the user and working with real files! ☕🚀
We’re going to cover everything very slowly and clearly, like I’m sitting next to you in a quiet Bandra café, showing you every line on my laptop. We’ll use lots of real-life analogies, complete runnable examples, step-by-step explanations, common mistakes with fixes, and fun tips so it all sticks perfectly.
Let’s dive in!
1. Reading Input from User – readln() (The Modern Kotlin Way)
In Kotlin, the easiest and most recommended way to read input from the console is readln() (introduced in Kotlin 1.6+ — now standard in 2026).
readln() = read line → reads one full line of text from the user (including spaces) and returns it as String.
Basic example – Ask for name
|
0 1 2 3 4 5 6 7 8 9 10 11 |
fun main() { println("तुमचं नाव काय आहे?") val name = readln() // Waits for user to type and press Enter println("नमस्ते $name! तुम्ही खूप छान दिसता! 😊") } |
Run it → IntelliJ shows a console → type your name → press Enter → magic!
What happens if user just presses Enter?
- readln() returns an empty string (“”)
- Very safe and simple — no Scanner hell like Java!
Another example – Ask for age (convert to Int)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
fun main() { println("तुमचं वय किती आहे?") val ageInput = readln() // Safe conversion val age = ageInput.toIntOrNull() // Returns Int? (nullable) if (age != null) { println("वाह! तुम्ही $age वर्षांचे आहात!") } else { println("अरेरे, कृपया फक्त अंक टाका!") } } |
Important: readln() returns String → you must convert it to Int, Double, etc. yourself. Use toIntOrNull(), toDoubleOrNull(), etc. → they return null if conversion fails (super safe!)
2. Old Way: readLine() (Still Works, but Avoid)
Before Kotlin 1.6, we used readLine() — it’s exactly the same as readln(), just older name.
|
0 1 2 3 4 5 6 |
val input = readLine() // Same as readln() |
Modern recommendation (2026): Always use readln() — it’s clearer and future-proof.
3. Output – println() vs print()
| Function | What it does | New line? | Example |
|---|---|---|---|
| println() | Prints + adds newline (\n) | Yes | println(“Hello”) → Hello + new line |
| print() | Prints without newline | No | print(“Hi”) → Hi (cursor stays on same line) |
Examples
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun main() { print("नमस्ते ") print("Webliance! ") // No new line println("कसं काय?") // New line after this println("Line 1") println("Line 2") } |
Output:
|
0 1 2 3 4 5 6 7 8 |
नमस्ते Webliance! कसं काय? Line 1 Line 2 |
4. Beautiful String Formatting in Kotlin
Kotlin gives you three powerful ways to format strings:
Way 1: String Templates (Most common & beautiful)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
val name = "Webliance" val age = 25 val city = "Mumbai" println("नमस्ते $name! तुम्ही $age वर्षांचे आहात आणि $city मध्ये राहता!") // → नमस्ते Webliance! तुम्ही 25 वर्षांचे आहात आणि Mumbai मध्ये राहता! // Complex expression inside ${} println("Next year तुम्ही ${age + 1} वर्षांचे व्हाल!") |
Way 2: String.format() (like Java)
|
0 1 2 3 4 5 6 7 8 |
val score = 92.75 val message = "तुमचा स्कोअर आहे %.2f%%".format(score) println(message) // तुमचा स्कोअर आहे 92.75% |
Way 3: String interpolation with variables (same as templates)
|
0 1 2 3 4 5 6 7 8 |
val product = "Laptop" val price = 85000 println("Product: $product, Price: ₹$price") // Very clean! |
5. Simple File Reading & Writing (Intro to java.io + Kotlin Extensions)
Kotlin makes file I/O super simple with extension functions on File and Path.
Reading a Text File – One Line!
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.io.File fun main() { val file = File("data.txt") // Read entire file as one string val content = file.readText() println("File content:\n$content") // Read all lines as List<String> val lines = file.readLines() lines.forEachIndexed { index, line -> println("Line ${index + 1}: $line") } } |
Even shorter (Kotlin idiomatic):
|
0 1 2 3 4 5 6 7 8 |
File("data.txt").forEachLine { line -> println(line) } |
Writing to a File – Super Easy
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
fun main() { val file = File("output.txt") // Write text (overwrites if exists) file.writeText("नमस्ते Webliance!\nKotlin is awesome! 🚀") // Append text file.appendText("\nAdded on {java.time.LocalDate.now()}") println("File written successfully!") } |
Even nicer with use{} (auto close):
|
0 1 2 3 4 5 6 7 8 9 |
File("log.txt").bufferedWriter().use { writer -> writer.write("Log entry 1\n") writer.write("Log entry 2\n") } |
6. Quick Recap Table (Your Cheat Sheet)
| Feature | Kotlin Way (Best Practice) | Notes / Example |
|---|---|---|
| Read user input | readln() | val name = readln() |
| Print with newline | println(“Hello”) | Adds \n automatically |
| Print without newline | print(“Hi”) | Cursor stays on same line |
| String template | “Hello $name!” or ${age + 1} | Most loved feature! |
| Raw multi-line | “”” multi-line text “”” | No escape needed |
| Read file | File(“data.txt”).readText() or readLines() | Very simple |
| Write file | File(“out.txt”).writeText(“…”) | Overwrites |
| Append to file | File(“log.txt”).appendText(“…”) | Adds to end |
7. Common Newbie Mistakes & Fixes
| Mistake | Problem | Fix |
|---|---|---|
| Using readLine() instead of readln() | Old style – works but not idiomatic | Use readln() (new name) |
| Forgetting to convert input to Int | val age = readln() → String | Use readln().toIntOrNull() |
| Writing ; after every line | Looks like Java – not needed | Remove most semicolons |
| Not handling empty input | readln() returns “” if user just presses Enter | Check if (input.isBlank()) { … } |
| Writing to file without try-catch | IOException crashes | Use try-catch or use {} |
8. Homework for You (Let’s Make It Fun!)
- Basic Ask user for name and city using readln(). Print: “नमस्ते $name! तुम्ही $city मध्ये राहता!”
- Medium Ask user for two numbers → convert to Int safely → print their sum, difference, product.
- Advanced Ask user for email → print length using safe call + Elvis (if null → “No email provided”)
- Fun Create a file greeting.txt and write 3 lines using string templates (include current date).
- Challenge Read lines from a file names.txt → print only names longer than 5 characters.
You’ve just unlocked Kotlin’s beautiful I/O — your programs now talk to users and work with files like a pro!
