Checking for nulls in Kotlin

Kotlin’s type system is aimed to eliminate NullPointerException's from your code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
fun handleNullsExplicitly(name: String? = null): String? {
    return if (!name.isNullOrBlank()) name else "The one who shall remain nameless"
}

fun handleNullsWithElvisOperator(name: String? = null): String? {
    return name ?: return "The one who shall remain nameless"
}

fun main(args: Array<String>) {
    println(handleNullsExplicitly(""))
    // The one who shall remain nameless
    println(handleNullsExplicitly("Real Kotlin"))
    // Real Kotlin

    println(handleNullsWithElvisOperator())
    // The one who shall remain nameless
    println(handleNullsWithElvisOperator("Real Kotlin"))
    //Real Kotlin
}

You can handle nulls explicitly or using the ?: Elvis Operator and get rid of those pesky NPEs.

Updated: