fun checkLengthA(str : String?): Int = if (str.isNullOrBlank()) 0 else str.length
"Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String?
all null objects (or empty) are caught by isNullOrBlank(), so the str object in str.length can never be null (or empty). This can be achieved by replacing extension function with an explicit check.
fun checkLengthB(str : String?): Int = if (str == null) 0 else str.length
or less verbose expression:
fun checkLengthC(str : String?): Int = str?.length ?: 0
Both checkLengthB and checkLengthC will run without problems.
Let's remove the nullable type from checkLengthA to avoid the compile error, highlighted above:
fun checkLengthA(str : String): Int = if (str.isNullOrBlank()) 0 else str.length
Now, we are only allowed to pars use non-null parameter of type String, so if we expect some null types then we have to put the "?" back.
Looks like the complier does not understand that str of type String will never evaluate to null when running str.length and an extension function, but it will compile without problems if we use (str == null) in the if-else statement.
Can anyone explain why it is happening?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…