fun main() { val name: String? = null println(name?.length ?: "No name") }
The variable name is nullable and set to null. The safe call name?.length returns null because name is null. The Elvis operator ?: then returns the string "No name" instead of null. So the output is No name.
Adding ? after a type means the variable can hold either a value of that type or null. This is Kotlin's way to explicitly allow nulls and avoid null pointer exceptions.
fun main() { val text: String = null println(text.length) }
The variable text is declared as a non-nullable String but assigned null. Kotlin does not allow this and will produce a compilation error.
fun main() { val number: Int? = 10 number?.let { println(it * 2) } ?: println("No number") }
The variable number is 10, not null. The safe call number?.let executes the lambda, printing 10 * 2 = 20. The Elvis operator is ignored because the value is not null.
nonNullNames contain?fun main() { val names: List<String?> = listOf("Anna", null, "Bob", null, "Cara") val nonNullNames = names.mapNotNull { it?.uppercase() } println(nonNullNames.size) }
The list names has 5 items, 2 of which are null. The lambda it?.uppercase() returns uppercase strings for non-null items and null for nulls. mapNotNull filters out the nulls, so nonNullNames contains 3 items.