Why is `if (list?.isEmpty())` not allowed when `if...
# getting-started
f
Why is
if (list?.isEmpty())
not allowed when
if (list?.isEmpty() == true)
is? You are still not specifying null behaviour...
d
Yes, you are. Only
true
is equal to
true
.
false
,
null
and any other value is not equal to
true
.
2
f
list?.isEmpty()
will return null if
list
is null
s
list?.isEmpty()
returns
Boolean?
and comparing it to
true
lets you check if it’s true.
false
and
null
are two other states the if statement can’t make assumptions about. “not specifying null behavior” is only important if you’re using the
if
as an assignment expression, otherwise you just need to give it a non-nullable
Boolean
f
I see. Feels a bit weird, if statement and comparing to true not being the same. I guess next question is: Why does equals operator accept nullable arguments? Java compatibility?
d
Why would it not? How would you do
if (a == null)
otherwise?
f
That would be an equals method on nullable types. Like
fun Int?.equals(other: Int?): Boolean
d
I am not sure I see why that is any better than
==
.
Also, that would make it impossible to compare two things that you do not know the type of.
f
I guess better type safety? But yeah maybe it's not any better.
s
You can do
list != null && list.isEmpty()
or
list?.isEmpty() ?: false
if that's better for you.
j
You could also write an extension function like
Iterable?.isEmptyOrNull() = this == null || this.isEmpty()
or make it more specific to the classes you need to use it for
There's very little that is inconvenient about Kotlin
In my experience anyway