Lesson 2 of 8
Null Safety
Learn how Kotlin handles . and String? are different types, so the can stop you from writing code that would throw a NullPointerException.
fun main() {
var name: String = "Ada"
// name = null // compile error — String can't be null
var nickname: String? = null // String? CAN be null
// println(nickname.length) // compile error: might be null
// Safe call — returns null instead of crashing:
println(nickname?.length) // null
// Elvis operator — default when null:
val len = nickname?.length ?: 0
// Chains short-circuit on the first null:
// user?.address?.city ?: "unknown"
}fun describe(input: String?) {
// Smart cast: after the null check, the compiler
// treats 'input' as non-null String inside the block.
if (input != null) {
println("length is ${input.length}") // no ?. needed
}
// let: run a block only when non-null:
input?.let { s ->
println("got: $s")
}
}
fun main() {
// !! asserts 'trust me, not null' — crashes if wrong:
val risky: String? = null
// val boom = risky!!.length // NullPointerExceptionFinished reading?Mark it done to track your progress.
Tip: use the ← and → keys to move between lessons.