null safety

Java treats null as a value Kotlin treats nullable as a different type That distinction is the entire reason the language exists

Two types

val name: String = "Ada"
val maybe: String? = null

A plain String cannot be null A String? can The compiler enforces the difference

Safe call

val length = maybe?.length

If maybe is null, length is null No exception, no defensive if statement

Elvis

val result = maybe ?: "unknown"

Choose a fallback when the value is missing The operator is named after the shape of the symbol, not the singer

Not null assertion

val length = maybe!!.length

That tells the compiler you are sure If you are wrong, it throws at runtime Use it only when the surrounding code already proved it

Platform types

Java APIs do not carry nullability information Kotlin calls them platform types and leaves the choice to you That is the seam where null safety can leak

Next

Control flow in 04 control

Test this in your lab first

Posted