A missing value is represented by null, meaning that an object or reference value is absent. Kotlin makes this possibility explicit: ordinary types cannot contain null, while a question mark marks a nullable type such as String?. section 7.2
Handling a nullable string
A String? parameter may contain null, so Kotlin requires a check before accessing length. The example returns 0 for null and 3 for "abc"; a String parameter would reject null at compile time. section 7.2
Listing 7.1 Handling null values using if checks
fun strLenSafe(s: String?): Int =
if (s != null) s.length else 0 #1
fun main() {
val x: String? = null
println(strLenSafe(x))
// 0
println(strLenSafe("abc"))
// 3
}
Use this runnable example to connect nullable declarations, an if check, and the resulting values. section 7.2
Kotlin applies the rule consistently:
- Declaring a parameter as String guarantees that it contains a String instance. section 7.2
- Declaring a value as String? allows null, but direct method calls on it are rejected. section 7.2
- Passing a nullable value to a non-null parameter produces a compile-time type mismatch rather than a likely runtime NullPointerException. section 7.2 section 1.3.1
- This differs from familiar Java code, where calling length on a null String can throw NullPointerException at runtime. section 7.2


































