Null safety helps prevent errors when a program tries to use something that is missing or empty. Kotlin makes this easy and safe by design.
Why null safety is Kotlin's defining feature
var name: String = "John" // cannot be null var nickname: String? = null // can be null
Use ? after the type to allow a variable to hold null.
Without ?, Kotlin will not allow null values, preventing errors.
var message: String = "Hello" message = null // Error: Null can not be a value of a non-null type String
? allows the variable to hold null safely.var message: String? = "Hello" message = null // This is allowed
?. to safely access properties when the variable might be null.val length = message?.length // Safe call operator returns length or null
!! to assert a variable is not null, but it can crash if wrong.val length = message!!.length // Throws error if message is null
This program shows how Kotlin handles null safety. It prints the length of a non-null name, then safely tries to print the length of a nullable nickname which starts as null, then changes to a value.
fun main() { var name: String = "Alice" println("Name length: ${name.length}") var nickname: String? = null println("Nickname length: ${nickname?.length}") nickname = "Ally" println("Nickname length: ${nickname?.length}") }
Null safety helps avoid the common 'null pointer exception' errors found in many languages.
Using ? and safe calls ?. makes your code more reliable and easier to maintain.
Be careful with !! because it can cause crashes if the value is actually null.
Kotlin's null safety prevents many common bugs by making null explicit.
Use ? to allow nulls and safe calls ?. to handle them safely.
This feature makes Kotlin code safer and easier to understand.