Can anyone explain why the compiler can't smart ca...
# announcements
e
Can anyone explain why the compiler can't smart cast
b
in
b.isEmpty()
but it does for
a
in
a.isEmpty()
?
Copy code
val a: String? = null
val b: String? = null
when {
  a == null && b == null -> true
  a == null -> b.isEmpty()
  b == null -> a.isEmpty()
}
k
Someone should correct me if I'm wrong but in this case it can smart cast
a
because you null check it prior so it cannot be null by the time it gets to executing
isEmpty()
while
b
can be null and the compiler can't 'smart cast'. You can fix this by null checking
b
prior and handing the null case or using
b?.isEmpty() ?: true
.
To clarify the 'smart cast' in this scenario is the cast from nullable to nonnull types. E.g
Boolean?
->
Boolean
e
@karn Assuming the first clause of the where is false and the second is true: 1.
a
and
b
cannot both be null 2.
a
is null 3. Since
a
is null and both
a
and
b
cannot be null,
b
must be not null
1