Mis on 'nullable' tüübid Kotlinis ja kuidas nad toimivad?
sobes.tech AI
Vastus AI-lt
Nullable types in Kotlin are types that can hold either a value or null. They are explicitly marked with a ? symbol after the type name.
The operation is based on Kotlin's type system, which prevents NullPointerException at compile time. The compiler requires an explicit null check before accessing members of a nullable type.
Main ways to safely work with nullable types:
-
nullcheck usingif:fun printLength(str: String?) { if (str != null) { println(str.length) // Safe call after null check } else { println("String is null") } } -
Safe call operator (
?.): Returnsnullif the object isnull, otherwise the result of the call.val safeLength: Int? = str?.length // If str is null, safeLength will be null -
Elvis operator (
?:): Provides a default value if the expression on the left isnull.val lengthOrDefault: Int = str?.length ?: 0 // If str is null, lengthOrDefault will be 0 -
Explicit not-null assertion operator (
!!): Converts a nullable type to a non-nullable type. Use with caution, as it will throw aNullPointerExceptionif the value isnull.val assertedLength: Int = str!!.length // Will throw NPE if str is null -
let/run/apply/alsofunctions with safe call:str?.let { // Code executes only if str is not null println("String length: ${it.length}") }
Kotlin's nullable type system significantly enhances safety and reduces the likelihood of NullPointerException compared to languages where null can be assigned to any type without explicit indication.