What happens if you access a nullable object field in Kotlin?
sobes.tech AI
Answer from AI
If you access a nullable object's field without checking for null, a NullPointerException (NPE) will occur.
To safely access it, you can use the following approaches:
-
Safe call operator (
?.): Returnsnullif the object isnull, otherwise performs the call.// Assume user? is User? val userName: String? = user?.name -
Not-null assertion operator (
!!): Explicitly confirms that the object is notnull. If it isnull, aNullPointerExceptionis thrown.// Use consciously, may lead to NPE val userName: String = user!!.name -
Elvis operator (
?:): Provides a default value if the object to the left of?:isnull.val userName: String = user?.name ?: "Unknown User" -
iforwhenblocks: Explicit null check.if (user != null) { val userName = user.name } else { // Handle case when user is null } -
Functions
let,run,apply,withwith safe call:user?.let { // `it` inside this block is non-nullable `User` val userName = it.name }
The choice of approach depends on the program logic and the desired behavior when the object is null. Usually, it is recommended to use the safe call operator (?.) or the Elvis operator (?:) to avoid NPE. The !! operator should be used with caution.