Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between var name: String? and var name: String

Tags:

kotlin

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) {
//...
}
like image 698
januprasad Avatar asked May 22 '17 05:05

januprasad


3 Answers

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.
//...
}
like image 125
chandil03 Avatar answered Oct 09 '22 06:10

chandil03


String? can be null and String can not be null, that's about all there's to it.

like image 20
Jan Vladimir Mostert Avatar answered Oct 09 '22 04:10

Jan Vladimir Mostert


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

like image 2
Alenkart Rodriguez Avatar answered Oct 09 '22 04:10

Alenkart Rodriguez