1. Why separate parsing from input
When you write a small learning main, it’s very easy to mix everything into one mess: “printed a hint → read a line → parsed it right away → complained right away → decided what to do next right away”. With 10 lines it feels fine. With 30 it already looks like instant noodles: you can kind of eat it, but it’s embarrassing to show to people.
The problem isn’t that input is “bad”. The problem is that input is about communicating with a human, while parsing is about converting text into a value. If these two tasks live in the same place, you lose reuse: tomorrow you’ll need to parse a string not from the console but, for example, from a variable (or a test), and you’ll suddenly discover that your “parser” prints prompts. Awkward.
Another reason is debugging. A “clean” parser can be tested on specific strings: "10", " 10 ", "", "abc". You don’t even need a user for that, which means fewer accidents and more control (and fewer chances to argue with the keyboard about why it typed the wrong thing again).
What is a “clean parser”, and why should it be “quiet”
By a “clean parser” in this lecture we’ll mean a simple thing: it’s a function that accepts a String and returns a T?, and it doesn’t read anything and doesn’t print anything. It works like a small converter: you give it a string → you get a value, or null if the string is “not in the right format”.
Such a parser is sometimes called “quiet”: it doesn’t scold in the console and doesn’t explain who’s to blame. And that’s not because we’re insensitive. It’s because the parser must not decide how exactly to react. The reaction depends on the scenario: sometimes we want to ask the user to enter again, sometimes to exit the program, sometimes to accept a default value. The parser doesn’t know that and must not know it.
Notice the naming convention: the OrNull suffix in Kotlin often means “we’ll return null if it didn’t work”. The standard library follows this idea in various places (for example, some operations have *OrNull versions that return null instead of crashing). We do the same thing, but for parsing user input.
2. String normalization
Almost any user input needs a bit of “prep”. A person may add spaces, accidentally press space at the end, type “YES” in caps, or type “Yes” with different casing. A computer is a straightforward creature: it doesn’t “understand what you meant” unless you explicitly programmed it. So we introduce an intermediate step: normalization.
Normalization is not “rule validation” (that’s the next lecture). It’s specifically bringing text to a form that’s convenient to work with: remove leading/trailing spaces; if needed, convert to lowercase. Our goal is that different “semantically identical” variants become identical strings.
Below are two small functions we’ll use as building blocks:
fun normalizeTrim(raw: String): String {
return raw.trim()
}
fun normalizeCommand(raw: String): String {
return raw.trim().lowercase()
}
There’s an important detail here: trim() removes spaces at the edges, but doesn’t touch spaces inside. That is, " Hello world ".trim() becomes "Hello world". And that’s fine: if a person really entered two spaces inside, that might be part of the text.
To see how this works “live”, you can make a small main:
fun main() {
val raw = " YeS "
val t = normalizeTrim(raw)
val c = normalizeCommand(raw)
println("raw='$raw'") // raw=' YeS '
println("trim='$t'") // trim='YeS'
println("cmd='$c'") // cmd='yes'
}
Notice: we’re not arguing yet whether this is “good” input. We’re just transforming it into a convenient form.
Mini diagram of the pipeline “input → normalization → parsing”
flowchart LR
A["raw String
as entered by the user"] --> B["normalize
trim/lowercase"]
B --> C["parse…OrNull
String → T?"]
C --> D["the scenario decides
what to do with null"]
3. Number parsers: Int and Double
When we previously wrote readIntOrNull(prompt), we did three things at once: printed the prompt, read the string, parsed it. Now we separate these tasks.
parseIntOrNull: parse a number without the console
We need a parser that does two things: first it normalizes the string (at least trim()), then it tries to parse. If the string is empty after trim(), we return null (because “empty” is definitely not a number, and that’s better than hoping for a miracle).
fun parseIntOrNull(raw: String): Int? {
val s = raw.trim()
if (s.isEmpty()) return null
return s.toIntOrNull()
}
Notice: there is no println, no readln(). This is a pure function: same raw → same result. Which means it’s easy to use anywhere.
Let’s test it on different inputs:
fun main() {
println(parseIntOrNull("10")) // 10
println(parseIntOrNull(" 10 ")) // 10
println(parseIntOrNull(" ")) // null
println(parseIntOrNull("10 years")) // null
}
And here it’s very useful to mentally distinguish situations: " " is not a “program bug”, it’s a normal “data doesn’t fit” situation. We return null and let the scenario decide what to do next.
Table “what it was → what it became”
| raw (input) | after trim() | result of parseIntOrNull |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
parseDoubleOrNull: numbers with a dot
With Double it’s almost the same story, just the method is called toDoubleOrNull(). And there’s a subtle human-world detail: some people enter "3.14", while others habitually write "3,14". Kotlin (and the JVM) expects a dot by default. We for now won’t “fix the world”, otherwise we’ll quietly drift into a more complex normalization topic. At this stage an honest contract is enough: dot means a number; comma means null.
fun parseDoubleOrNull(raw: String): Double? {
val s = raw.trim()
if (s.isEmpty()) return null
return s.toDoubleOrNull()
}
Mini check:
fun main() {
println(parseDoubleOrNull("2.5")) // 2.5
println(parseDoubleOrNull(" 2.5 ")) // 2.5
println(parseDoubleOrNull("2,5")) // null
println(parseDoubleOrNull("")) // null
}
If it feels like you’d want to accept "2,5" as "2.5", you’re thinking in the right direction. It’s just that today our task is to separate parsing from input and introduce basic normalization (trim, lowercase). More “bold” normalizations are better done consciously, otherwise you can silently break input where a comma is part of the text.
4. Command parsing: parseYesNoOrNull
Numbers are great, but console programs often ask “yes/no”, “y/n”, “ok/not ok”. And here lowercase() becomes our best friend: you don’t want to list in when the variants "YES", "Yes", "yEs", because that’s how you accidentally invent a new alphabet.
Let’s make a parser that accepts a string and returns Boolean?: true for “yes”, false for “no”, null if the answer is unclear.
fun parseYesNoOrNull(raw: String): Boolean? {
val s = raw.trim().lowercase()
return when (s) {
"yes", "y", "da", "d" -> true
"no", "n", "net", "n" -> false
else -> null
}
}
Why Boolean? and not just Boolean? Because otherwise we’d have to “assign” some default answer. And that’s already a scenario decision. The parser should honestly say: “I didn’t understand”.
Check:
fun main() {
println(parseYesNoOrNull(" YES ")) // true
println(parseYesNoOrNull("n")) // false
println(parseYesNoOrNull("yeah")) // null
}
Notice how neatly normalization “sits” here: we don’t list 20 casing variants because we lower-case the string once.
5. How to connect input and parsing
Now we have “clean” parsers. But a console program still has to read input. And this is where a very pleasant composition appears: the input utility stays small and dumb (in a good way), while the conversion logic moves into parse…OrNull.
Here’s a reminder of the “zero level” from the previous lecture (one of the possible variants):
fun readLine(prompt: String): String {
print(prompt)
return readln()
}
readln() reads a whole line from standard input. Then we can make input “wrappers” that use our parsers—and it will look very smooth and uniform:
fun readIntOrNull(prompt: String): Int? {
val raw = readLine(prompt)
return parseIntOrNull(raw)
}
fun readDoubleOrNull(prompt: String): Double? {
val raw = readLine(prompt)
return parseDoubleOrNull(raw)
}
This may look like an “extra step”, but in practice it wins in several places at once: you can change parseIntOrNull without touching input, and vice versa. Also, you can parse strings that didn’t come from the console using the same functions.
Small demo: “parser without the console”
fun main() {
val textFromSomewhere = " 42 "
val x = parseIntOrNull(textFromSomewhere)
println("x = $x") // x = 42
}
The scenario doesn’t read input, doesn’t print prompts, but reuses the same parser. That is the core idea of the lecture: parsing becomes a separate “building block”.
6. Mini example: user questionnaire
To avoid staying at the abstraction level, let’s take a small scenario we’ll evolve throughout the day: a console “questionnaire” that asks for a name, age, and whether you “agree to continue”. Today we won’t do re-entry and we won’t introduce a separate rule-validation layer (like “age 0..150”)—that will be the next lecture. We’ll just read carefully and parse safely.
Here’s how a main that uses our functions might look:
fun main() {
val nameRaw = readLine("Name: ")
val name = nameRaw.trim()
val age = readIntOrNull("Age: ")
val agree = parseYesNoOrNull(readLine("Continue? (yes/no): "))
println("name='$name' age=$age agree=$agree")
// Example: name='Ira' age=20 agree=true
}
Notice an interesting thing: for name we don’t do ...OrNull yet. We just do trim(), because “non-empty name” is already a rule (validation), not parsing. Today our goal is to learn not to mix layers.
If you want to do the same thing in a more “API-like” way, you can extract reading the “yes/no” answer into a function that uses the parser:
fun readYesNoOrNull(prompt: String): Boolean? {
val raw = readLine(prompt)
return parseYesNoOrNull(raw)
}
And then main becomes a bit more of a “story of actions”, not a set of technical details:
fun main() {
val name = readLine("Name: ").trim()
val age = readIntOrNull("Age: ")
val agree = readYesNoOrNull("Continue? (yes/no): ")
println("name='$name' age=$age agree=$agree")
}
There’s a bit of self-irony here: yes, we wrote a few functions just so that main becomes 3 lines shorter. But it’s like doing the dishes: at first it feels like “meh, later”, and then suddenly you run out of kitchen.
7. Common mistakes
When you first separate parsing from input, your brain often resists: “why so complicated, I can just do toIntOrNull() right in main”. That’s a normal stage, like denial before acceptance. Below are the most common rakes people step on in this exact topic.
Mistake #1: the parser starts printing to the console.
It’s very tempting to do inside parseIntOrNull something like println("Enter a number!"). But then the function stops being universal: you’ll want to use it elsewhere (for example, when processing a command string), and it suddenly starts talking to the user. Keep the parser “quiet”: it returns T?, and messages are the scenario’s job.
Mistake #2: forgot trim() and got “magic null”.
Beginners often get surprised: “I entered 10, why is it null?”. And then it turns out it was "10 " (a trailing space) or " 10" (a leading space). Without trim(), such cases become micro-bugs that annoy more than big errors because they look “random”. Do trim() inside the parser, and input becomes noticeably more human-friendly.
Mistake #3: mixing parsing and validation, and the parser grows into a monster.
If you start checking ranges, “not less than 1”, “not more than 100”, and other business conditions right inside parseIntOrNull, the function quickly becomes too specific. Today the parser answers “is this an integer at all?”. The question “does it fit the rules?” is better moved to a separate layer (and we’re heading there next in the day’s plan).
Mistake #4: returning false instead of null in parseYesNoOrNull.
The logic “if unclear, then no” seems convenient, but it mixes two different meanings: “the user said no” and “we didn’t understand what they said”. As a result, the scenario loses the ability to respond correctly to unclear input. Boolean? is more honest here: true/false/null explicitly encode three different states.
Mistake #5: creating a “universal parser for everything” with a bunch of flags.
Sometimes there’s an urge to write one function like parseNumberOrNull(raw, allowDouble, allowComma, defaultValue, ...). It looks powerful, but reads heavily and almost always leads to parameter confusion. At the level of our course it’s better to keep a few small, obvious functions: parseIntOrNull, parseDoubleOrNull, parseYesNoOrNull. Small functions are easier to test, explain, and reuse.
GO TO FULL VERSION