Reading — step 1 of 5
Learn
~1 min readStrings and Null Safety
Kotlin's standout feature is null safety — types are non-nullable by default. To allow null, suffix the type with ?:
val name: String = "Alice" // never null
val label: String? = null // can be null
// label.length // ✗ compile error
label?.length // safe call — returns null if label is null
label?.length ?: 0 // Elvis operator — default value
label!!.length // !! — assert non-null (throws if null)
This eliminates the NullPointerException class of bugs from your code (mostly — !! and Java interop can still trigger it). The compiler tracks nullability through your code automatically.
fun greet(name: String?) {
if (name != null) {
println(name.length) // ✓ smart-cast — compiler knows it's non-null here
}
}
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…