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?.lengthisnulland.lengthis never evaluated. Your first example is effectively doing:The
!!operator says "throw aNullPointerExceptionif 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 assignnulldirectly 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 thelengthproperty becausenullis not a reference.You can force it to give you to
NullPointerExceptionby 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
nulldirectly to a var though, so what's happening under the hood to getUnresolved referenceis just a guess.