Klitos Kyriacou
09/20/2023, 3:53 PMb
is not null in the following and doesn't require !!
?
if (a != null || b != null) {
if (a == null) {
val c: Any = b!!
}
}
Casey Brooks
09/20/2023, 4:00 PMb != null
expression, so within that block the compiler doesn’t really have any hard facts about b
within that scope.
Doing if (a == null && b != null)
instead does give you the smart-cast, and it also removes the extra if-statement.Klitos Kyriacou
09/20/2023, 4:16 PMval a = something...
val b = something else...
if (a != null || b != null) {
// some code...
if (a == null) {
// do something with the obviously not null b
}
if (b == null) {
// do something with the obviously not null a
}
// some more code...
}
Ruckus
09/20/2023, 4:20 PMb
seems wrong. The compiler will see the entire expression, and absolutely should be able to infer the truthiness, regardless of what could happen at runtime.a == null
, this expression didn't short circuit". It's just a matter of complexity of the static analysis.Casey Brooks
09/20/2023, 4:25 PMwhen {
a != null && b == null -> { /* only a is non null */ }
a == null && b != null -> { /* only b is non null */ }
a != null && b != null -> { /* a and b are both non null */ }
a == null && b == null -> { /* a and b are both null */ }
}
Ruckus
09/20/2023, 4:29 PMa
and/or b
are expressions and not just variables, you either need to extract them to variables or repeat the expressions multiple times, which can sometimes negatively affect readability or scoping as much as the flattening improved it. And that assumes there isn't interspersed logic around the various checks like there is here.// some code...
and // some more code...
chunks out to separate functions, that could then be called in the flattened blocks that @Casey Brooks showed. That could help reduce duplication while still making the logic clear.dmitriy.novozhilov
09/20/2023, 7:38 PMKlitos Kyriacou
09/24/2023, 1:59 PM