Reputation: 1
folks!
We know, IF statement only works with true condition. The operator ? checks and guarantees firstName property is not null. So, if firstName isn't null and isEmpty() is also true, why "==true" is needed?
Shortly, why simple condition "firstName?.isEmpty()" is invalid?
class Person (firstName: String?) {
init {
if (firstName?.isEmpty() == true) {
println("firstName is null")
}else{
println("The name is $firstName")
}
}
}
Upvotes: 0
Views: 90
Reputation: 13505
Do note that the code does not work as intended (i.e. prints null if it is null or empty) https://pl.kotl.in/H7rBIT8H6
fun main() {
var firstName:String? = null
if(firstName?.isEmpty() ==true){
//print("firstName is null")
print("test1: TRUE. ") //<<-- THIS WILL NOT BE PRINTED
}else {
print ("test1: FALSE. ") // <<-- THIS IS RETURNED INSTEAD
}
firstName = ""
if(firstName?.isEmpty() ==true){
print("test2: TRUE. ") //<<--WORKS AS INTENDED
}else {
print ("test2: FALSE. ")
}
firstName = "Hello"
if(firstName?.isEmpty() ==true){
print("test1: TRUE. ")
}else {
print ("test1: FALSE. ") //<<--WORKS AS INTENDED
}
}
The output is
test1: FALSE. test2: TRUE. test1: FALSE.
notice "test1" is FALSE?
what is happening is the code
"firstName?.isEmpty()" returns null if firstName is null. and consequently, "null == true" will return false
So instead, what you should do is either call
firstName.isNullOrEmpty()
or
firstName==null || firstName?.isEmpty()==true
Upvotes: 0
Reputation: 15552
It is because firstName?.isEmpty()
can be true
, false
, or null
.
if (null)
does not make sense
UNLESS you are using a language that implicitly converts null
to true
or false
.
Kotlin does not implicitly convert it.
Upvotes: 1
Reputation: 7882
The operator ? checks and guarantees firstName property is not null.
No, safe call operator doesn't guarantees this. It guarantees that you won't get NullPointerException
if firstName
is null, instead you will get null
as a result of
firstName?.isEmpty()
expression.
So, the type of this expression is Boolean?
, and if
condition must be Boolean
.
I believe, you'd better use firstName.isNullOrEmpty()
here.
Upvotes: 3
Reputation: 2212
IsEmpty will be called in this case only if firstName is not null
Upvotes: 0
Reputation: 331
The issue here is that your list is nullable. In Kotlin you should always avoid having nullable values. I would suggest refactoring.
Anyway, the answer is:
isEmpty()
will not be called so you will not get a boolean value or condition which is needed for if.isNullOrEmpty()
insteadUpvotes: -1