1. Why input in main turns into a giant wall of code
When you’re just starting out, everything looks harmless: a couple of print() calls in main, a couple of readln(), and you’ve already got someone’s age, height, and favorite number. But 15 minutes go by, and suddenly your main looks like an accounting report that’s 40 lines long: it’s all about input, and almost nothing about the meaning of the program. And that’s not because you’re a bad programmer—it’s a normal growth stage.
Imagine we’re building a simple console “profile form.” Naive code usually looks like this:
fun main() {
print("Name: ")
val name = readln()
print("Age: ")
val ageStr = readln()
val age = ageStr.toIntOrNull()
if (age == null) {
println("Age was entered incorrectly.")
return
}
println("Hi, $name! You are $age years old.")
// Hi, Alex! You are 20 years old.
}
Does it work? Yes. Is it convenient to extend? Not really anymore. Because as soon as you add “height,” “weight,” “postal code,” and a couple more fields, you’ll start copying the same pattern by hand. And copy-paste is like wet snow: at first it’s “no big deal,” and then suddenly you slip and faceplant into a bug.
In Kotlin (and in programming in general), the typical response to repetition is to extract the repeated chunk into a function.
2. Prompt and the readLine(prompt) utility
prompt is a parameter, not a string sitting next to the code
The word prompt here means “a hint to the user before input.” It’s literally the text you print: "Age: ", "Enter width: ", and so on. It seems like a small thing, but that small thing is responsible for two important qualities of a program: usability for a human and readability of the code.
Right now, our prompt almost always looks like two lines: print("..."), then readln(). And that creates duplication. If we learn to pass the prompt into a function as a parameter, we can write shorter and cleaner: “call the function, and it will show the prompt and read the input.” No magic—just discipline: hide repetitive code inside a function.
It’s important to lock in the idea: an input utility should do exactly one job—help you obtain a value. It should not “decide the fate of the program,” choose a scenario branch, print long lectures about errors, and so on. That belongs in main (or other scenario code), where the context is clearer.
readLine(prompt): read a string with a prompt
Let’s start with the simplest (and very useful) function: print the prompt, read the line, return the line. Super simple—but it already removes copy-paste.
fun readLine(prompt: String): String {
print(prompt)
return readln()
}
fun main() {
val city = readLine("City: ")
println("You entered the city: $city") // You entered the city: Boston
}
Notice an important point: the function is called readLine, even though Kotlin has its own readLine() (which used to return a nullable). Here we use readln(), the modern variant that returns String and expects that input will actually be present (for a learning console, that’s fine). In our tasks, “the user didn’t enter anything at all and stdin ended” is rare, and we won’t complicate things yet.
One more point: for now we do not call trim(), we don’t normalize spaces, and we don’t change case. That’s intentional. Input like " Bob " will be returned as-is. We’ll leave this as a “small pain” to fix in the next lecture, when we talk about clean parsing and normalization.
3. Safe parsing and ...OrNull functions
readIntOrNull(prompt): Int?
Now let’s add the most common case: the user must enter an integer. The key idea: not toInt(), because toInt() will throw an exception on an invalid format and crash the program. What we want now is predictable behavior: invalid input → null.
Let’s make a function with an honest name: readIntOrNull. The OrNull suffix is like a road sign: “careful, there may be null here.” The calling code is required to handle it.
fun readIntOrNull(prompt: String): Int? {
print(prompt)
val s = readln()
return s.toIntOrNull()
}
fun main() {
val age = readIntOrNull("Age: ")
println("age = $age") // age = 20 (or age = null)
}
Why this is convenient:
The input code became compact, and more importantly—uniform. If you have 10 fields, you’ll call readIntOrNull(...) 10 times instead of writing the same print/readln/toIntOrNull chain 10 times. And if you decide to improve the input (for example, add trim()), you’ll fix it in one place.
A small “gotcha” that’s useful to know upfront: if the user enters " 10 " (with spaces), toIntOrNull() will return null. And that’s fine for this lecture: we’re building a basic brick for now. In the next lecture we’ll talk separately about input normalization—and that’s where we’ll add trim() as a systematic solution.
readDoubleOrNull(prompt): Double?
In console tasks, Double appears no less often than Int: price, height, weight, GPA, coordinates, “how many hours you slept.” And here we also want safe input so that "3,14" or "three.four" doesn’t turn the program into a pumpkin.
The structure is exactly the same—and that’s good: it’s easier for the brain to remember when functions look alike.
fun readDoubleOrNull(prompt: String): Double? {
print(prompt)
val s = readln()
return s.toDoubleOrNull()
}
fun main() {
val height = readDoubleOrNull("Height (in meters): ")
println("height = $height") // height = 1.82 (or height = null)
}
Real-life note: many users enter decimals with a comma ("1,82"). toDoubleOrNull() doesn’t understand that because it expects a dot. We won’t solve this head-on yet, because that’s already “normalization and rules”—the next step. For now, our goal is: don’t crash and honestly return null.
Diagram: read → parse → return T?
So this sticks not as a set of spells but as a clear process, let’s draw a mini flowchart. It’s the same for Int, Double, and any other types you’ll parse later.
flowchart TD
A["Function readXOrNull(prompt)"] --> B["print(prompt)"]
B --> C["raw = readln()"]
C --> D[attempt parse raw]
D --> E{did it work?}
E -- yes --> F[return value T]
E -- no --> G[return null]
The point is that the function must not crash and must not make decisions for the scenario. It only converts a string into a value, if possible.
The Kotlin approach with helper functions like this for input is very common: you can see similar readInt()/readStr() even in practical problem solutions to shorten input code.
toInt() vs toIntOrNull() (and friends)
Beginners very often confuse “safe parsing” with “regular parsing.” Let’s sort it out so you don’t get surprises later.
| What we do | Method | What it returns for "123" | What happens for "12a" |
|---|---|---|---|
| Parse Int “directly” | |
|
exception (program crashes) |
| Parse Int safely | |
|
|
| Parse Double “directly” | |
|
exception |
| Parse Double safely | |
|
|
That’s why with user input we almost always start with ...OrNull: input is “dirty,” and that’s normal. We don’t have to take the user’s word for it—especially if they’re typing at 2 a.m.
4. How to write scenario code with T?
Elvis and early exit
The appearance of Int? and Double? means your scenario must be able to live with null. And this is where two extremes often show up: either the person starts writing huge nested ifs, or they use !! (and the program crashes again, just with a sense of guilt).
Let’s use a readable pattern: “if it didn’t work, report it and exit.” The Elvis operator ?: works great for this together with run { ... }, where we can execute a couple of lines and do a return.
fun readIntOrNull(prompt: String): Int? {
print(prompt)
return readln().toIntOrNull()
}
fun main() {
val age = readIntOrNull("Age: ") ?: run {
println("Age must be an integer.")
return
}
println("OK, age accepted: $age") // OK, age accepted: 20
}
Why this looks good:
The “happy path” doesn’t drown in if (age != null) { ... }. We’re basically saying: “get the age, and if it didn’t work—here’s the reaction and we exit.” It’s a very human style: first the safety net, then the main logic.
Mini app: profile form
So we have a shared code story, let’s put together a small scenario: ask for name, age, and height. We won’t add complex rules yet (ranges, “not empty,” repeated input)—that will come later. Today we practice one thing: compress the input template into small functions.
Here’s a compact version of the program at the current knowledge level:
fun readLine(prompt: String): String {
print(prompt)
return readln()
}
fun readIntOrNull(prompt: String): Int? {
print(prompt)
return readln().toIntOrNull()
}
fun readDoubleOrNull(prompt: String): Double? {
print(prompt)
return readln().toDoubleOrNull()
}
fun main() {
val name = readLine("Name: ")
val age = readIntOrNull("Age: ") ?: run {
println("Age must be an integer.")
return
}
val height = readDoubleOrNull("Height (m): ") ?: run {
println("Height must be a number (for example, 1.82).")
return
}
println("Profile: $name, $age years old, height $height m")
// Profile: Alex, 20 years old, height 1.82 m
}
Notice: we don’t argue with the user, we don’t try to “guess” what they meant. If the input is incorrect, we honestly say so and exit. That’s a normal policy for the beginning. Later we’ll learn to make programs more “patient” and ask the user to enter it again—but we don’t mix everything together at once.
5. Common mistakes
Mistake #1: use toInt() / toDouble() for user input.
It looks simpler, but in practice it turns any invalid character into a program crash. Today we practice the opposite style: “input errors are an expected situation,” so toIntOrNull() and toDoubleOrNull() provide more stable control.
Mistake #2: name the function readInt even though it returns Int?.
A name is a promise. If you called it readInt, a person (including you a week later) expects Int, not “maybe null, maybe not null.” The OrNull suffix isn’t bureaucracy—it’s a way to make the code self-documenting: you see the name and immediately understand the risk.
Mistake #3: print long error messages inside the utility.
It’s tempting to have readIntOrNull print “You entered nonsense!”, “Try again!”, “I’m disappointed in you!” But then the utility stops being universal: in one place you ask for age, in another for width, in a third for number of attempts, and the message is still the same and out of place. Better: the utility returns null, and the scenario decides what exactly to tell the user.
Mistake #4: try to fix all input problems inside the first version of the function.
For example, add trim(), replace commas with dots, allow an empty string as 0, and five more “smart” heuristics. That makes the function unpredictable: today it “guessed,” tomorrow it “guessed wrong.” We move in small steps: first a basic brick, then normalization (next lecture), then rule validation (later).
Mistake #5: turn main into a forest of nested ifs.
When you get an Int?, your hand reaches for if (x != null) { if (y != null) { if (z != null) { ... }}}. It’s hard to read. A cleaner style at our level is Elvis ?: + run { ...; return } to quickly end the scenario on input error and keep the “happy path” straight and clear.
GO TO FULL VERSION