1. Why you need ?. and ?:, and why a plain if is not enough
When you first learn about null, the usual first reaction is: “OK, I’ll just write if (x != null) everywhere.” That’s a fine start, but pretty soon you’ll feel the pain: nested ifs grow, the logic sprawls across the code, and reading the program starts to feel like going through a labyrinth (and at the end you may still meet a minotaur).
Kotlin offers more expressive constructs: short operators that make null handling part of the expression. This matters because many tasks are not “do the action or don’t”, but “get the value if it exists, otherwise use a fallback”. That’s exactly what ?. and ?: are for.
To keep the picture in your head, here is a mini table:
| Operator | How to read it | Idea | What it returns |
|---|---|---|---|
|
“if not null — do it, otherwise return null” | safe access | most often T? |
|
“if the left side is null — take the right side” | default value / fallback behavior | often removes nullable |
|
“I swear this is not null” | forced access | T, but with a crash risk |
Next, we will go through each tool calmly and with examples.
2. Safe call ?.: safe access without crashes
People usually like ?. because it makes code shorter and safer. But the main point is that it makes the behavior explicit: right in the line of code you show that the value may be absent, and that you are prepared for that scenario. It’s like fastening a seat belt: you’re not planning an accident, but life feels calmer.
?. on properties: .length without risk
The simplest example is a string length. If the string is nullable, direct access is forbidden:
fun main() {
val nickname: String? = null
println(nickname.length) // not allowed: nickname can be null
val len: Int? = nickname?.length
println(len) // null
}
Here it’s important to notice one thing: the result of nickname?.length has type Int?, because the operation might “not happen” (if the left side is null, there is nothing to compute a length for).
And that is super logical: a safe call doesn’t “invent” a length out of thin air. It honestly says: “Either I return the length, or I return null.”
?. on methods: safe call of uppercase()
The same principle applies to methods:
fun main() {
val nickname: String? = "neo"
val upper: String? = nickname?.uppercase()
println(upper) // NEO
}
If nickname is null, then upper will also become null, and the program will not crash.
Safe call chains: a “domino of ?.”
Typically ?. is not used just once but as a chain: “take the string → trim spaces → convert to uppercase → take the length”. And at each step the value may become null (if the input was null).
fun main() {
val raw: String? = " Kotlin "
val len: Int? = raw
?.trim()
?.uppercase()
?.length
println(len) // 6
}
It reads nicely: while the value exists — keep going; as soon as it doesn’t — the whole chain becomes null.
Mini diagram: what ?. does
To reinforce it, let’s represent how ?. works as a small flowchart:
flowchart TD
A["Do we have a value x: T?"] --> B{ x == null? }
B -->|yes| C["Result = null"]
B -->|no| D["Execute x.member / x.func()"]
D --> E["Result = value"]
Yes, the operator looks like two characters, but there is very concrete logic behind it.
3. The ?: operator
The ?: operator (Elvis, because it resembles Elvis Presley’s hairstyle) lets you replace null with a normal value (or a normal action).
Elvis as a “default value”
The most common form:
fun main() {
val nickname: String? = null
val len: Int = nickname?.length ?: 0
println(len) // 0
}
Notice the type: on the left, nickname?.length produces Int?, but Elvis substitutes 0, so the final result is a regular Int.
This is one of the key patterns: ?. often “produces nullable”, and ?: often “removes nullable”.
Elvis and string messages: good UX in the console
In our console programs it’s important not only to “not crash”, but also to talk to the user in a human-friendly way.
fun main() {
val nickname: String? = null
val label: String = nickname?.uppercase() ?: "ANONYMOUS"
println("Hello, $label!") // Hello, ANONYMOUS!
}
If the value exists — we format it nicely. If it doesn’t — we show fallback text.
Elvis as an early exit
Sometimes null is not “let’s substitute 0”, but “we can’t continue”. Then instead of a default value we do an early exit from the function.
Kotlin allows using return together with Elvis:
fun parsePositiveInt(text: String): Int? {
val x: Int = text.toIntOrNull() ?: return null
if (x <= 0) return null
return x
}
fun main() {
println(parsePositiveInt("42")) // 42
println(parsePositiveInt("oops")) // null
println(parsePositiveInt("-5")) // null
}
The idea is: we “localize the problem” immediately. If parsing fails — return null and don’t build nested ifs.
4. Trust me, bro
The !! operator looks like a simple way to “silence the compiler”: it converts T? into T. But it does it very straightforwardly: if the value turns out to be null, the program crashes at runtime (usually with KotlinNullPointerException).
Important idea: !! does not make your code safer. It makes your code compilable, and shifts safety onto your confidence.
Example: compiles, but crashes
fun main() {
val nickname: String? = null
val len: Int = nickname!!.length
println(len) // the program will not reach here
}
If you run this code, you will get a crash. That is, !! is not “handling null”, it is “I guarantee it’s not null”.
When !! can make sense at all
No fanaticism: !! can be treated like an emergency button “break glass in case of fire”. Sometimes it’s appropriate when you are absolutely sure the value cannot be null, and if it suddenly is null — that really is a bug that is better to detect immediately.
But in practice, when a beginner uses !!, it often means: “I didn’t understand how to handle null properly.” So the basic rule is simple: first look for a solution via ?., ?: or an if check, and only then (in rare cases) consider !!.
4. User questionnaire: optional fields and handling null
Let’s keep developing the same console app: a simple “user questionnaire”. Previously we read strings, did trim(), and parsed numbers via toIntOrNull(). Now we will add optional fields (that can be skipped) and apply ?., ?: and clean patterns.
Agree on meaning: empty string vs null
A very common confusion: the user pressed Enter and entered an empty string "". That is not null. But for our logic, “entered nothing” often means “no value”. So we can convert an empty string into null ourselves.
Let’s make a small helper function:
fun emptyToNull(text: String): String? {
val trimmed = text.trim()
return if (trimmed.isEmpty()) null else trimmed
}
Read a nickname as String? and format the output
fun emptyToNull(text: String): String? {
val trimmed = text.trim()
return if (trimmed.isEmpty()) null else trimmed
}
fun main() {
println("Enter a nickname (can be empty):")
val nicknameInput = readln()
val nickname: String? = emptyToNull(nicknameInput)
val label = nickname?.uppercase() ?: "ANONYMOUS"
println("Your label: $label") // if empty: "Your label: ANONYMOUS"
}
Here we use two tools at once: ?.uppercase() and ?: "ANONYMOUS".
Age: toIntOrNull() returns Int?, and that is fine
Now ask for the age, but make it optional (for example, the user doesn’t want to share).
fun emptyToNull(text: String): String? {
val trimmed = text.trim()
return if (trimmed.isEmpty()) null else trimmed
}
fun main() {
println("Enter age (can be empty):")
val ageText: String? = emptyToNull(readln())
val age: Int? = ageText?.toIntOrNull()
println("age = $age") // for example: age = 25 or age = null
}
A very important point: we cannot do ageText.toIntOrNull(), because ageText is nullable. So it’s either if or ?.. We chose ?..
Nice output: form a phrase, not “null”
Now let’s produce a normal message for the user:
fun emptyToNull(text: String): String? {
val trimmed = text.trim()
return if (trimmed.isEmpty()) null else trimmed
}
fun main() {
println("Enter age (can be empty):")
val ageText: String? = emptyToNull(readln())
val age: Int? = ageText?.toIntOrNull()
val ageLabel: String = age?.toString() ?: "not specified"
println("Age: $ageLabel") // for example: "Age: not specified"
}
Here we built another “bridge”: age is Int?, and Elvis converts it into text that you can print without embarrassment.
Pattern “handle null immediately”: avoid nesting
Imagine we want to estimate the “approximate birth year” (roughly 2026 - age). Important: 2026 here is just a year chosen for the example. If there is no age, calculating makes no sense.
Let’s make a function that returns a result string:
fun estimateBirthYear(ageText: String?): String {
val age: Int = ageText?.toIntOrNull() ?: return "Birth year: unknown"
val year = 2026 - age
return "Estimated birth year: $year"
}
fun main() {
println(estimateBirthYear("20")) // Estimated birth year: 2006
println(estimateBirthYear(null)) // Birth year: unknown
println(estimateBirthYear("abc")) // Birth year: unknown
}
Here Elvis is used not with a default value, but with default behavior: an early return.
Assembling the entire questionnaire
Let’s assemble a simplified version of the questionnaire: name is required; nickname and age are not.
fun emptyToNull(text: String): String? {
val trimmed = text.trim()
return if (trimmed.isEmpty()) null else trimmed
}
fun main() {
println("Name (required):")
val name: String = readln().trim()
println("Nickname (can be empty):")
val nickname: String? = emptyToNull(readln())
println("Age (can be empty):")
val ageText: String? = emptyToNull(readln())
val age: Int? = ageText?.toIntOrNull()
val shownNickname = nickname?.uppercase() ?: "ANONYMOUS"
val shownAge = age?.toString() ?: "not specified"
println("Profile: $name / $shownNickname / age: $shownAge")
// Example: "Profile: Alice / ANONYMOUS / age: not specified"
}
Here we have a neat “processing pipeline”:
readln() → trim() → (possibly) emptyToNull() → (possibly) ?.toIntOrNull() → formatting via ?:.
This is a normal style of working with nullable values: without extremes, but also without ignoring them.
5. Common mistakes when working with ?., ?:, and !!
Mistake #1: expecting ?. to substitute a default value.
Beginners sometimes read safe call like: “if it’s null, it will somehow fix itself”. No: ?. only guarantees the program won’t crash when accessing a property/method. If the left side is null, the result of the expression will also be null. If you need a default, that is Elvis ?:, and the default should be meaningful, not just “so it compiles”.
Mistake #2: a ?. chain becomes long and stops being readable.
Technically you can write five or six safe calls in a row, and it will even work. But the human brain is not a compiler: it’s hard to keep long chains in mind, especially if there is also ?: at the end. In such cases it is better to introduce intermediate vals and give them clear names, so the code reads like steps, not like a spell.
Mistake #3: using ?: 0 or ?: "" without meaning, thereby masking a problem.
Elvis is very tempting: add ?: 0 — and everything “works”. But sometimes this hides an input error or breaks the logic. For example, age 0 can be a valid number in math, but for a questionnaire it is more like an oddity. It’s better to choose defaults that make sense for your domain: “not specified”, “unknown”, “—”, or an early return if further logic is meaningless without the value.
Mistake #4: fixing every compiler error with !!.
!! really does “fix” the compiler message quickly, because it converts T? into T. But the price is a runtime crash risk, often in a place where you don’t expect it (especially if the value came from user input). At your stage it is much more correct to treat !! as a rare tool for situations where crashing on null is a deliberate contract, not as a universal hammer for every nail.
Mistake #5: confusing null and an empty string, and therefore combining ?. and ?: in strange ways.
If you have not agreed on what “the user entered nothing” means, you will get surprises. An empty string "" is a value, and ?. does not apply to it at all (it is not null). So it is often useful to explicitly normalize input, converting “empty after trim()” into null. Then ?. and ?: start working exactly as you expect, and the program becomes predictable.
GO TO FULL VERSION