I'm new to Kotlin Programming lang.
I've been developing apps in android.
I found a data class taking constructor with String?
and String
Can anyone make me understand this.
data class Person(var name: String?) {
//...
}
data class Person(var name: String) {
//...
}
When you use ?
, it tells, you can have null value also. Because Kotlin enforces null safety.
See comments in following code:
data class Person(var name: String?) { // This can have null value also
//...
}
data class Person(var name: String) { // This can not have a null value, it will give compile time error.
//...
}
String?
can be null and String
can not be null, that's about all there's to it.
The "?" operator defines the null-ability of a variable.
Examples:
Accept String type but also accept null value.
var x :String? = ""
x = null // works fine
Only accept String type, in case you intent to set it's value to null will provoke a compilation error.
var x :String = ""
x = null // will provoke a compilation error.
It's important to keep in mind after you check the null value of a variable it will be automatically cast to non-nullable type.
fun test() {
var x: String? = ""
x = null // works fine
x = "String type" // works fine
if(x == null) {
println("The var x can't be null")
return
}
x = null // will provoke a compilation error.
}
fun main(args: Array<String>) {
test()
}
Kotlin Documentation, null-safety
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With