1

I'm from the java android background. So can someone explain why a variable with type String? cannot be equal to a variable of type String.

var a: String? = "Kotlin"
var b: String = "Kotlin"

b = a // Gives error

What's the difference in both the types ? Can anyone explain in java ?

3 Answers 3

3

In kotlin the "?" keyword indicates that a data type can take a null value. Variable "a" can take a null value, but variable "b" can not take a null value. You would need to make sure that "a" is not null before you could assign that value to "b".

Sign up to request clarification or add additional context in comments.

2 Comments

Hmm.. so I can reverse them ? As the "a" can take the null value. I can assign "b" value to "a" ?
@AravindChowdary Yes, you could reverse them and assign the value of "b" to "a".
2

If you want to assign the value of a to b you can do like this

var a: String? = "Kotlin"
var b: String = "Kotlin"
b= a?:"" -----> if a is null at some point of time in your code then b would be assigned an empty value

or

 b= a.toString() -----> if a is null at ssome point of time in your code then b would be assigned "null" string value

Comments

1

The following prints "it's the same". Are you using the correct comparison operator?

var a: String? = "Kotlin"
var b: String = "Kotlin"

if (a == b){
    println("it's the same");
}
else{
    println("it's not the same!")
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.