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) {
//...
}

      

+3


source to share


5 answers


String?

can be null, and String

can not be null, that's about everything there.



+1


source


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.
//...
}

      

+6


source


"?" 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()
}

      

Kotlin Documentation, null safety

+1


source


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

      

0


source


?

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

-3


source







All Articles