fun main() { val name: String? = null println(name?.length ?: "No length") }
The variable name is nullable and set to null. Using name?.length safely returns null instead of throwing an error. The Elvis operator ?: then provides the fallback string "No length".
fun main() { val number: Int = null println(number) }
Kotlin types are non-nullable by default. Assigning null to a non-nullable type causes a compilation error.
fun main() { val text: String? = null val length: Int = text!!.length println(length) }
The !! operator asserts that the value is not null. Since text is actually null, this causes a NullPointerException at runtime.
Kotlin's type system makes all types non-nullable by default. To allow null values, you must explicitly declare a type as nullable using ?.
fun main() { val map: Map<String, String?> = mapOf("key" to null) val length = map["key"]?.length ?: -1 println(length) }
The map contains a key with a null value. The safe call ?.length returns null, so the Elvis operator returns -1.
