What is the difference between the name var: String? and var name: String
I am new to Kotlin programming programming. I am developing applications in Android. I found that the data class takes a constructor with String?
and String
can anyone make me figure it out.
data class Person(var name: String?) {
//...
}
data class Person(var name: String) {
//...
}
source to share
When you use ?
it says that you can also have a null value. Because Kotlin provides zero security .
See comments in the 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.
//...
}
source to share
"?" the operator defines the null capacity of the variable.
Examples:
Accept String, but also null.
var x :String? = ""
x = null // works fine
Only accepting a String type if you intend to set it to null will cause a compilation error.
var x :String = ""
x = null // will provoke a compilation error.
It is important to remember that after you check the null value of a variable, it will be automatically added to the invalidated 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()
}
source to share
A variable declared with ? , indicates that the variable may or may not be null.
Otherwise, it is interpreted as a nonzero value.
Such a feature was explicitly added to Kotlin to mitigate / prevent a common runtime error, NullPointerException .
For example,
var a: String? = "abc"
a.length // Compile Time Error, trying to access possibly null value
var b: String = "xyz"
b.length // No Error, the value is never null
Having said that, you can argue that the value is not null by using !!
which will remove the compiler error but add the NPE risk:
var a: String? = "abc"
a!!.length // Will cause Run Time Exception if a is null
source to share
?
will be for a safe cast operator for kotlin . Ex. if we have a broadcast operation like:
val x: String = y as String
and if y
- null
, then the above code throws an exception. To avoid this, we can use the safe cast operator ( ?
). The above snippet would look like this:
val x: String? = y as? String
This will return null
if there is any glitch during casting. Please find the link here
source to share