https://kotlinlang.org logo
Title
f

Fredrik Pe

03/21/2019, 1:50 PM
Why is
if (list?.isEmpty())
not allowed when
if (list?.isEmpty() == true)
is? You are still not specifying null behaviour...
d

diesieben07

03/21/2019, 1:50 PM
Yes, you are. Only
true
is equal to
true
.
false
,
null
and any other value is not equal to
true
.
2
f

fred.deschenes

03/21/2019, 1:51 PM
list?.isEmpty()
will return null if
list
is null
s

Shawn

03/21/2019, 1:52 PM
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

Fredrik Pe

03/21/2019, 2:18 PM
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

diesieben07

03/21/2019, 2:18 PM
Why would it not? How would you do
if (a == null)
otherwise?
f

Fredrik Pe

03/21/2019, 2:21 PM
That would be an equals method on nullable types. Like
fun Int?.equals(other: Int?): Boolean
d

diesieben07

03/21/2019, 2:22 PM
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

Fredrik Pe

03/21/2019, 3:07 PM
I guess better type safety? But yeah maybe it's not any better.
s

SiebelsTim

03/21/2019, 3:28 PM
You can do
list != null && list.isEmpty()
or
list?.isEmpty() ?: false
if that's better for you.
j

Justin

03/22/2019, 1:22 AM
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