1. Why nullable chains are needed
When you’re just starting to work with null, the most natural move is to write checks if (x != null) and do the required work inside. That’s fine: millions of programmers thought this way before us, and some still do (sometimes even successfully). But as soon as you add a second processing step, then a third, a fourth—your ifs start to “grow downward”, and the code turns into a ladder you want to prop up with a stool.
Imagine a typical input flow: the user entered a string → we trimmed it → tried to parse a number → validated the range → computed the result. If you write this via nested ifs, you’ll get many indentation levels and constant “what if it’s null here?”. Nullable chains let you write the same logic linearly: “here’s a step, here’s a step, here’s a step, and if at some step there’s no value— here’s the fallback.”
Our goal today is to learn two basic patterns:
- x?.let { ... } — execute the block only if x is not null, and inside the block it is already not nullable.
- x?.let { ... } ?: ... — a linear form of “if it worked—take the result, otherwise—use the fallback scenario.”
And yes, Kotlin explicitly positions let as one of the functions that help “simplify expressions” and keep processing close to the data.
2. ?.let { ... }: process only if a value exists
let is a scope function where the object is available as it, and the result is the last expression in the block. An important detail specifically for nullable work: when you write x?.let { ... }, the block runs only if x != null. And inside let, Kotlin already understands that it is not null, so it allows calling methods and properties without additional checks.
Let’s start with a very simple example: read a number; if it worked—print its square. If it didn’t—do nothing at all.
fun main() {
val raw = readln()
val n: Int? = raw.toIntOrNull()
n?.let { value ->
val sq = value * value
println("square = $sq") // if you entered 7 -> square = 49
}
}
Note: here we do not decide what to do in the null case. That can be OK when the action is truly optional (for example, debug printing, “we’ll try—if it fails, oh well”). But in real scenarios you more often need to definitely have a result—and then ?.let alone is not enough; you need the pattern with Elvis ?:.
Another example: we have a string and want to bring it to a “normal form” (trim + lowercase), but only if the string exists at all.
fun main() {
val maybeText: String? = readln().takeIf { it.isNotBlank() }
val normalized: String? = maybeText?.let { it.trim().lowercase() }
println(normalized) // if you entered " HeLLo " -> hello
// if you entered empty/spaces -> null
}
Here normalized is also nullable. And that’s logical: if there’s no input, there’s nothing to normalize. But if later in your code you need non-nullable text (for example, for a report), it’s time to “close” null into a specific behavior.
3. The pattern ?.let { ... } ?: fallback
In a regular if-else, you explicitly write two branches. Elvis ?: does the same thing, but as an expression: on the left is the “main path,” on the right is the “backup.” And ?.let is convenient to put on the left, so the main path is computed only when there is a value.
Meaning of the pattern:
- left: “if x is not null—compute the result”
- right: “otherwise—return/compute the fallback”
Example: read a number. If it’s valid—double it. If not—use 0.
fun main() {
val raw = readln()
val n: Int? = raw.toIntOrNull()
val doubled: Int = n?.let { it * 2 } ?: 0
println("doubled = $doubled") // entered 21 -> doubled = 42
// entered "kitten" -> doubled = 0
}
Key point: doubled is not nullable, because to the right of ?: we provided a concrete value 0. That is, we “closed” the uncertainty.
A very common practical story: you want to treat an empty string as “absence,” not as real input. Then the combination takeIf → ?.let → ?: works great.
fun main() {
val token: String? = readln()
.trim()
.takeIf { it.isNotEmpty() }
val lower: String = token?.let { it.lowercase() } ?: "<empty>"
println(lower) // entered " Kotlin " -> kotlin
// entered "" -> <empty>
}
Here takeIf turns a “bad value” into null, and ?: turns null into a clear default.
So you don’t have to keep this in your head as “magic,” let’s pin down a mini table:
| Form | When the block runs | What is returned | Typical meaning |
|---|---|---|---|
|
only if x != null | the block result, but the nullable chain may continue | “try to process if it exists” |
|
the block—if x exists, otherwise fallback | always a value (usually non-null) | “normal result or a backup” |
4. Elvis ?: as a “contract”: a result is required
Many people initially perceive the Elvis operator ?: as “kind of replacing null with 0.” And yes, that’s one option. But a more mature view is that it’s a tool that helps you lock in a contract: “at this point the program must obtain a value.”
For example, you write a function readTopN(): Int, and it must return a proper number (non-nullable), because later you want to use topN without checks. So inside you can work with Int?, but at the end—close null with a default.
fun readTopN(): Int {
val raw = readln().trim()
val n: Int? = raw.toIntOrNull()
return n?.takeIf { it > 0 } ?: 5
}
fun main() {
val topN = readTopN()
println("topN = $topN") // entered 3 -> topN = 3
// entered -10 -> topN = 5
// entered "abc" -> topN = 5
}
In this example a detail matters: takeIf { it > 0 } can also return null if the number doesn’t fit. And that’s good: we honestly say “doesn’t fit—so it’s as if there is no value,” and then Elvis selects the default.
A small but useful fact: in Kotlin, Elvis is often used not only for values, but also to do an early return or throw—because the right side can be any expression. We won’t dive deep into exceptions now, but “early exit” will be useful today.
5. run { ... } as a multi-line fallback
Sometimes on the right of ?: it’s not enough to write 0 or "<empty>". Sometimes you want to: print a message to the user, choose a default value, maybe prepare something—and only then return a result. And that’s where many beginners try to write something odd like:
// don't do this; it's an example of "how you can get confused"
val x = n ?: println("bad") // println returns Unit, and everything starts breaking
To do multiple actions on the right side of Elvis, use run { ... }. It’s a regular function that executes the block and returns the last expression. So it’s a perfect “container” for a multi-line fallback.
fun main() {
val n: Int? = readln().toIntOrNull()
val value: Int = n ?: run {
println("This is not a number; I'll use the default value") // message
10 // last expression = result
}
println("value = $value") // entered 5 -> value = 5
// entered "hi" -> message + value = 10
}
Note: run { ... } here is not an “object scope function,” it’s just a block expression. We’re not using this; we don’t need it. We need “several lines of code that compute a value.”
The same trick works great for an “early exit” from main if the user didn’t provide required data.
fun main() {
val textOrNull: String? = readln().trim().takeIf { it.isNotBlank() }
val text: String = textOrNull ?: run {
println("Empty input—nothing to analyze. Exiting.")
return
}
println("We'll analyze: $text") // if we got here, text is definitely not empty
}
Notice how readable it is: on the left we described the “normal path,” on the right—“what we do if there’s no data.” No nested ifs, no extra indentation level.
6. A template for a console Text Analyzer
Now we’ll take a small but very practical step toward the future Text Analyzer: we’ll learn to read required text and optional settings so that main looks like a script, not a “validation factory.” We’re not counting frequencies and not building top-N yet—that will be the next lecture. But we’ll prepare input so it’s easy to add a pipeline later.
First, let’s make a utility: read a non-blank line or return null. It’s tiny, but it already removes half the pain.
fun readNonBlankLineOrNull(prompt: String): String? {
print(prompt)
return readln().trim().takeIf { it.isNotBlank() }
}
fun main() {
val text: String = readNonBlankLineOrNull("Enter text to analyze: ") ?: run {
println("Empty. So, no analysis today.")
return
}
println("OK, text accepted: \"$text\"")
}
Now add a “setting”: the user can enter topN, or can leave it blank. If it’s blank or garbage—use a default, for example 5. Here we’ll use ?.let and Elvis.
fun readIntOrNull(prompt: String): Int? {
print(prompt)
return readln().trim().toIntOrNull()
}
fun main() {
val text: String = readNonBlankLineOrNull("Enter text to analyze: ") ?: run {
println("Empty. So, no analysis today.")
return
}
val topN: Int = readIntOrNull("How many words to show (Enter = 5): ")
?.takeIf { it > 0 }
?: 5
println("Text: \"$text\"") // example: Text: "kotlin is great"
println("topN = $topN") // example: topN = 5
}
And here it’s important to feel the “taste” of the approach: topN at the end is not nullable, which means later, in the next lectures, you’ll calmly use topN without if (topN != null).
If you’re thinking “can it be shorter?”, then yes, it can. But our goal is not the shortest line count—it’s a readable script.
7. Where to close null, and where to improve readability
A very typical beginner mistake is to accidentally drag nullable too far, and then be surprised that Kotlin “keeps asking for ?..” In fact Kotlin isn’t being picky: it honestly reminds you that you yourself didn’t decide what “no value” means.
There are two healthy options.
- Option 1. You consciously keep T? further along, because “absence of a value” is a normal state. For example, in settings: the user may not specify a filter, and then there is no filter. In this case, nullable is part of the contract, and that’s fine.
- Option 2. You “close” nullable into a concrete behavior: a default value, a message + return, or “fail” (but that’s already closer to require/check and exceptions—we’ll be careful today).
A practical hint: if a function is supposed to “provide a result to continue the scenario,” try to return a non-nullable value, and hide nullable stuff inside. For example:
fun readPositiveIntOrDefault(prompt: String, default: Int): Int {
print(prompt)
val n: Int? = readln().trim().toIntOrNull()
return n?.takeIf { it > 0 } ?: default
}
fun main() {
val topN = readPositiveIntOrDefault("Top N (Enter = 5): ", default = 5)
println("topN = $topN") // Enter -> topN = 5
}
Nullable chains are great as long as they stay chains of 2–4 steps. But Kotlin lets you write 14 steps on one line. And that’s where “cryptograms” begin: the code is formally correct, but it’s scary to touch.
There’s a simple criterion: if inside let you start writing a mini algorithm or a second nested let appears—it’s better to stop and make the code a bit more “flat.”
For example, this is hard to read (especially for a beginner):
fun main() {
val result = readln().trim().takeIf { it.isNotBlank() }
?.let { it.toIntOrNull() }
?.let { it * 10 }
?: 0
println(result)
}
Yes, it works. But it’s not immediately clear at a glance what happens at each step. Better to name the values:
fun main() {
val raw: String = readln()
val token: String? = raw.trim().takeIf { it.isNotBlank() }
val n: Int? = token?.toIntOrNull()
val result: Int = n?.let { value -> value * 10 } ?: 0
println(result) // entered "7" -> 70
}
This version is a couple of lines longer, but you can explain it out loud without stumbling.
One more small life hack: if a chain uses it, and you feel that “it is no longer the same one”— just name the parameter.
val message: String = readIntOrNull("Enter age: ")
?.let { age -> "You are $age years old" }
?: "Age not recognized"
println(message)
With age it’s easier to read than with the “fifth it of the day.”
8. Common mistakes
Mistake #1: write x?.let { ... } and forget that the result still can be null.
This happens all the time: people are happy they removed an if, and then are surprised that later they still need ?. and ?:. The cure is simple: if you need a non-nullable result later, close the chain right away with the Elvis operator and choose a concrete behavior.
Mistake #2: use !! where you need Elvis.
!! means “I swear it’s definitely not null, programmer’s honor.” Sometimes that’s justified, but in user input it almost never is. If a value can be missing—use ?: with a default, or ?: run { ...; return }. Then the program behaves predictably instead of crashing on the first “kitten” instead of a number.
Mistake #3: try to make a multi-line fallback without run { ... } and accidentally get Unit instead of a value.
When you call println(...) on the right side of ?:, remember that println returns Unit. So an expression like val x = n ?: println(...) either won’t compile or will lead to weird types. If you need to print and return a value—wrap it in run { ... }.
Mistake #4: turn chains into a “magic conveyor belt” that nobody understands.
Scope functions and nullable chains are tools for readability, not a competition in minification. If the chain became long, if it repeats and gets confusing, if you yourself are not sure what type is currently “flowing” through the pipe—stop, introduce intermediate vals, or extract a step into a named function. Code should be understandable not only to the compiler, but also to you tomorrow morning.
GO TO FULL VERSION