Nullable Types
Deslize para mostrar o menu
Kotlin introduces a powerful approach to handling null values, which helps you avoid one of the most common errors in programming: the null pointer exception. In Kotlin, every variable must explicitly state whether it can hold a null value. By default, variables are non-nullable, meaning they cannot be assigned null. If you want a variable to be able to store null, you must declare it as a nullable type by appending a question mark (?) to its type. This design enforces safer code and reduces runtime errors related to null values.
Main.kt
12345678910111213141516171819package com.example fun main() { val nonNullableString: String = "Hello, Kotlin!" // The following line would cause a compile-time error: // nonNullableString = null val nullableString: String? = null println("Non-nullable: $nonNullableString") println("Nullable: $nullableString") // Safe call operator usage println("Length of nullable string: ${nullableString?.length}") // Elvis operator usage val lengthOrZero = nullableString?.length ?: 0 println("Length or zero: $lengthOrZero") }
In the code above, you see both non-nullable and nullable variable declarations. The variable nonNullableString cannot be assigned null, so attempting to do so would result in a compile-time error. The variable nullableString, declared with the String? type, can safely store a null value.
To access properties or methods of a nullable variable, you use the safe call operator (?.). This operator allows you to call a method or access a property only if the variable is not null, otherwise it returns null. For example, nullableString?.length will return the length if nullableString is not null, or null if it is.
When you want to provide a default value in case the variable is null, you use the Elvis operator (?:). This operator evaluates the expression on its left; if it is not null, that value is returned. If it is null, the expression on the right is used instead. In the example, nullableString?.length ?: 0 will return the length of the string if it is not null, or 0 if it is.
Obrigado pelo seu feedback!
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo