SDSnipDojo
← All lessons
Lesson 10 / 126 steps3 exercises

Null Safety

Nullable types, the Elvis operator, and safe calls.

1. Nullable types

In Kotlin, a regular String cannot be null. To allow null, write String?:

val name: String  = "Ada"     // never null
val maybe: String? = null     // ok

The compiler refuses to call methods on a nullable value until you've checked for null. After the check, it knows the value is non-null and lets you proceed:

fun lengthOrZero(s: String?): Int {
    if (s == null) return 0
    return s.length            // OK — compiler knows s is non-null here
}

2. lengthOrZero

Implement lengthOrZero(s) returning s.length, or 0 if s is null. Check with if (s == null) return 0.

Starter code

fun lengthOrZero(s: String?): Int {
    return 0
}

3. ?: — the Elvis operator

?: (it looks like Elvis if you tilt your head) returns the left side if it's not null, otherwise the right side:

val name: String? = null
val out = name ?: "anon"        // "anon"

It's the cleanest way to provide a fallback. You can chain it with anything that produces a nullable value:

fun lengthOrZero(s: String?) = (s?.length) ?: 0

4. nameOr with Elvis

Implement nameOr(name, fallback) returning name if not null, else fallback. Use the Elvis operator: return name ?: fallback.

Starter code

fun nameOr(name: String?, fallback: String): String {
    return fallback
}

5. ?. — safe calls

?. only invokes the method if the receiver isn't null. The whole expression is null when the receiver is:

val s: String? = null
val len: Int? = s?.length      // null

val s2: String? = "hi"
s2?.length                     // 2

Pair safe calls with Elvis to handle null neatly:

val len = s?.length ?: 0       // 0 when s is null, else s.length

Quick comparison: ?: replaces a null with a fallback; ?. propagates null through a method call.

6. firstChar with safe call

Implement firstChar(s) returning the first character of s (as a Char), or null if s is null. Use s?.first().

Starter code

fun firstChar(s: String?): Char? {
    return null
}

Run this Kotlin lesson in your browser

SnipDojo ships an in-browser Kotlin editor with the exercises above already wired to tests. Sign in with Google to edit the starter code, run it, and track your progress toward the free certificate — no installs and no local toolchain.

Sign in to run this code →