As i was going through Null saftey in Kotlin, here in hyperskill THEORY it was mentioned that Kotlin has a real remedy for NPE.
Consider below code (1) from Oliver Charlesworth
class Foo {
val c: String // Non-nullable
init {
bar()
c = "" // Initialised for the first time here
}
fun bar() {
println(c.length) // Oh dear
}
}
fun main(args: Array<String>) {
Foo()
}
Now above will give NPE. To avoid it, Kotlin uses '?'
code(2)
val c:String? = null
fun bar() {
print(c?.length)
}
Also instead of that i could have used like,
fun bar() {
if(c != null){
print(c.length)
}
}
Question
1.If i could just use if statement than why would i use code (2) ?
2.Is it because of code (2)'s conciseness ? or there is more to it that i am missing ?
I'm not sure if I fully understand your question. Object initialization is one of the very few cases where null safety in Kotlin is partially disabled. This is mentioned in the documentation about the null safety:
Possible explanations are: technical limitations imposed by the underlying Java; or intentional decision, because guaranteed null-safety during the initialization might be pretty annoying for the developer. No matter the reason, developers are expected to be careful when implementing the initialization logic or better, at all avoid complex logic there.
Answering your question on which code sample is better. None of them. Ideally, we should use simply
println(c.length), but make sure it never executes before initializingc.Update
If your concerns are not at all related to object initialization, but only about the
ifversus?.. First, your code samples aren't the same. First code sample always invokesprint(), potentially passingnullto it. Second code sample doesn't invokeprint()in the case of null.But general answer is: yes, this is for conciseness. In Java we often have to write code like this (let's ignore Law of Demeter):
In Kotlin this is simply: