I was curious how does Kotlin handle nulls, more specifically, I mean:
class aClass(val input : Int ){
val field = input
}
fun main() {
val obj : aClass? = null
if(obj?.field == null) {
println("true returned")
}
}
In this part of code the object obj of type aClass? is initiated as a null, and despite the field field was not initialized the if statement checking if field is equal to null returns true. I know in Java it would throw an error that field is not initialized and we would need to first check if the object is null and then if field is null.
I couldn't find the answer anywhere. So my question is how does Kotlin do it? Does it consider every field of a null object as null by default or does it initilize this object with all fields equal to null, maybe it just checks if object is null and doesnt even check the field field and returns true, or maybe something else?
CodePudding user response:
?.
is the safe call operator. When you use it to call a function or property on a nullable variable and that variable currently is null, it directly returns null without calling that function or property. If that property or function usually returns a non-nullable type, the result of a safe call will be a nullable version of that type.
obj?.field
is shorthand for (if (obj == null) null else obj.field)
.
The official documentation describes it here.
CodePudding user response:
Maybe it just checks if object is null and doesnt even check the field
field
Exactly. This is what the ?.
safe navigation operator does. a?.b
evaluates to null
immediately, if a
is null, and doesn't evaluate b
at all. So in your case, obj?.field
evaluates to null
because obj
is null.
On the other hand, if you had used !!.
instead of ?.
, it would throw an exception (NullPointerException
) if obj
is null.
I couldn't find the answer anywhere.
Info about ?.
is here. Stuff about !!
is on the same page,
You can also refer to the Kotlin Language Specification on the navigation operators section, or the not-null assertion expressions section.