Thuta Learning
BasicProgrammingbeginner

Null Safety (? !!)

Relax. We'll talk through this in plain words — no textbook voice.

One of the big features that made Kotlin so popular is Null Safety. In programming, null values are a very common cause of errors. By default, Kotlin doesn't let a variable hold null, and protects against it at the compiler level. If you want a variable to be nullable, you add ? after the type.

kotlin
fun main() {
    var username: String = "thutatech"
    // username = null // Error: non-null String ထဲ null ထည့်လို့မရပါ။

    var nickname: String? = "Sai"
    nickname = null

    println(username)
    println(nickname)
}
You should see
thutatech null

Summary

In Kotlin, Type and Type? are not the same. ? tells the compiler that the value could be null.

Easy traps

  • Using a nullable variable directly as if it were non-null causes a compile error.
Null Safety (? !!) | Thuta Learning