CodeGym /행동 /Kotlin SELF /null handling tools: ?., ?:, !!

null handling tools: ?., ?:, !!

Kotlin SELF
레벨 11, 레슨 3
사용 가능

1. Why we need ?. and ?:, and why if alone 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 starting point, but pretty soon you’ll feel the pain: nested if blocks grow, the logic spreads across the code, and reading the program starts to feel like walking through a labyrinth (and a minotaur may still be waiting at the end).

Kotlin offers more expressive constructs: short operators that make null handling part of an expression. This matters because many tasks are not “do something or don’t”, but “get a value if it exists; otherwise use a fallback”. That’s exactly what ?. and ?: are for.

To keep the picture in your head, here’s a mini table:

Operator How to read it Idea What it returns
?.
“if it’s 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 nullability
!!
“I swear this is not null” forced access T, but with a crash risk

Next, we’ll go through each tool calmly, 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 can be missing, 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.

?. with 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 may 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 could “not happen” (if the left side is null, there is nothing to compute the length from).

And that’s perfectly logical: a safe call does not “invent” a length out of thin air. It honestly says: “Either I’ll return the length, or null.”

?. with 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 won’t crash.

Safe call chains: “a ?. domino”

Typically, ?. is used not once, but as a chain: “take a string → trim spaces → uppercase → take length”. And at each step the value can 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—we keep going; as soon as it doesn’t—the whole chain turns into null.

Mini diagram: what ?. does

To reinforce it, let’s represent ?. as a small flowchart:

flowchart TD
    A["Value exists 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 it encodes very specific logic.

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 result is a regular Int.

This is one of the key patterns: ?. often “produces nullability”, and ?: often “removes it”.

Elvis and string messages: decent console UX

In 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—format it nicely. If not—show fallback text.

Elvis as an early return

Sometimes null is not “let’s substitute 0”, but “we can’t continue”. Then instead of a default we do an early return 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—we return null and don’t build nested if blocks.

4. Trust me, bro

The !! operator looks like a simple way to “shut up the compiler”: it turns T? into T. But it does this very literally: if the value turns out to be null, the program crashes at runtime (usually with KotlinNullPointerException).

Key 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 never reach here
}

If you run this code, you’ll get a crash. In other words, !! is not “handling null”, it is “I guarantee it’s not null”.

When !! can be appropriate

No fanaticism: !! can be seen as an emergency “break glass in case of fire” button. Sometimes it is appropriate when you are absolutely sure the value cannot be null, and if it suddenly is null—that’s truly a bug you’d rather catch immediately.

But in practice, when a beginner uses !!, it often means: “I didn’t understand how to handle null correctly.” 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 form: optional fields and handling null

Let’s continue evolving the same console app: a simple “user form”. Earlier we read strings, applied trim(), and parsed numbers via toIntOrNull(). Now we’ll add optional fields (that may be skipped), and apply ?., ?:, and neat 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 write a small helper function:

fun emptyToNull(text: String): String? {
    val trimmed = text.trim()
    return if (trimmed.isEmpty()) null else trimmed
}

Read 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("닉네임을 입력하세요(비워도 됨):")
    val nicknameInput = readln()
    val nickname: String? = emptyToNull(nicknameInput)

    val label = nickname?.uppercase() ?: "ANONYMOUS"
    println("표시 라벨: $label") // if empty: "표시 라벨: ANONYMOUS"
}

Here we use two tools at once: ?.uppercase() and ?: "ANONYMOUS".

Age: toIntOrNull() returns Int?, and that’s fine

Now let’s ask for age, but make it optional (for example, the user may not want to share it).

fun emptyToNull(text: String): String? {
    val trimmed = text.trim()
    return if (trimmed.isEmpty()) null else trimmed
}

fun main() {
    println("나이를 입력하세요(비워도 됨):")
    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 can’t write ageText.toIntOrNull(), because ageText is nullable. So we need 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("나이를 입력하세요(비워도 됨):")
    val ageText: String? = emptyToNull(readln())

    val age: Int? = ageText?.toIntOrNull()

    val ageLabel: String = age?.toString() ?: "미입력"
    println("나이: $ageLabel") // for example: "나이: 미입력"
}

Here we created another “bridge”: age is Int?, and Elvis turns it into text that you can print without embarrassment.

Pattern “handle null immediately”: avoid nesting

Imagine we want to estimate “birth year approximately” (roughly 2026 - age). Important: 2026 here is just an example year. If age is missing, computing is pointless.

Let’s make a function that returns a result string:

fun estimateBirthYear(ageText: String?): String {
    val age: Int = ageText?.toIntOrNull() ?: return "출생 연도: 알 수 없음"
    val year = 2026 - age
    return "대략적인 출생 연도: $year"
}

fun main() {
    println(estimateBirthYear("20"))   // 대략적인 출생 연도: 2006
    println(estimateBirthYear(null))   // 출생 연도: 알 수 없음
    println(estimateBirthYear("abc"))  // 출생 연도: 알 수 없음
}

Here Elvis is used not with a default value, but with a default behavior: early return.

Assembling the whole form

Let’s assemble a simplified version of the form: 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("이름(필수):")
    val name: String = readln().trim()

    println("닉네임(비워도 됨):")
    val nickname: String? = emptyToNull(readln())

    println("나이(비워도 됨):")
    val ageText: String? = emptyToNull(readln())
    val age: Int? = ageText?.toIntOrNull()

    val shownNickname = nickname?.uppercase() ?: "ANONYMOUS"
    val shownAge = age?.toString() ?: "미입력"

    println("프로필: $name / $shownNickname / 나이: $shownAge")
    // Example: "프로필: Alice / ANONYMOUS / 나이: 미입력"
}

Here we have a neat “processing pipeline”:

readln() → trim() → (optionally) emptyToNull() → (optionally) ?.toIntOrNull() → formatting via ?:.

This is a normal nullable-handling style: no extremes, but also no ignoring.

5. Common mistakes when using ?., ?:, and !!

Mistake 1: expecting ?. to substitute a default value.
Beginners sometimes read safe call like this: “if it’s null, it’ll somehow fix itself.” No: ?. only guarantees that the program won’t crash when accessing a property/method. If the left side is null, the result of the expression is also null. If you need a default, that’s Elvis ?:, and the default should be meaningful—not “anything that compiles”.

Mistake 2: a ?. chain becomes long and hard to read.
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’s also a ?: at the end. In such cases, it’s better to introduce intermediate vals and give them clear names, so the code reads like steps rather than like a spell.

Mistake 3: using ?: 0 or ?: "" without meaning, thereby masking the problem.
Elvis is very tempting: add ?: 0—and everything “works”. But sometimes that hides an input error or breaks your logic. For example, age 0 may be a valid number in math, but for a form it’s rather odd. It’s better to choose defaults that make sense for your domain: “미입력”, “알 수 없음”, “—”, or an early return if the further logic is pointless without a value.

Mistake 4: fixing all compiler errors with !!.
!! really can “fix” the compiler message quickly, because it turns T? into T. But the cost is the risk of a runtime crash—often in a place where you don’t expect it (especially if the value came from user input). At your stage, it’s 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: mixing up null and an empty string, which leads to strange combinations of ?. and ?:.
If you haven’t agreed on what “the user entered nothing” means, you’ll get surprises. An empty string "" is a value, and ?. does not apply to it at all (it’s not null). That’s why it’s often useful to explicitly normalize input, turning “empty after trim()” into null. Then ?. and ?: work exactly as you expect, and the program becomes predictable.

1
과제
Kotlin SELF, 레벨 11, 레슨 3
잠금
환영 레이블
환영 레이블
1
과제
Kotlin SELF, 레벨 11, 레슨 3
잠금
유효 길이
유효 길이
1
과제
Kotlin SELF, 레벨 11, 레슨 3
잠금
업무 보고
업무 보고
1
과제
Kotlin SELF, 레벨 11, 레슨 3
잠금
액세스 코드
액세스 코드
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION