example:
fun main(){
var userInput: String?
//userInput = null
userInput = "asbdef"
var inputLength:Int? = userInput!!.length
println("Length of the string is :"+inputLength)
}
Output : Length of the string is :6
fun main(){
var userInput: String?
userInput = null
//userInput = "asbdef"
var inputLength:Int? = userInput!!.length
println("Length of the string is :"+inputLength)
}
Output : Unresolved reference: length
I want to know why it gives compile error?
If I just replace (!!) operator with (?) it compiles well but prints output as null.
PS: I'm newbie in Kotlin
The
?.
operator short-circuits if the left side evaluates tonull
. So the result ofnullVariable?.length
isnull
and.length
is never evaluated. Your first example is effectively doing:The
!!
operator says "throw aNullPointerException
if the left side is null. Otherwise, we know it's not null on the right side". You can see this if you change your second example a little:However, I'm not sure why are you are getting
Unresolved reference: length
. It looks like that the compiler is doing some optimization when you assignnull
directly touserInput
, so rather than compiling it to aString?
which throws an NPE at runtime, it knows the value is onlynull
(notString?
) at compile time, and therefore can't have thelength
property becausenull
is not a reference.You can force it to give you to
NullPointerException
by adding a layer of abstraction via a function call:I don't see anything n the Null Safety documentation about the difference in behaviour between initializing in one line / via a function call vs. assigning
null
directly to a var though, so what's happening under the hood to getUnresolved reference
is just a guess.