Is there a plan in the roadmap to make the compile...
# getting-started
k
Is there a plan in the roadmap to make the compiler know that
b
is not null in the following and doesn't require
!!
?
Copy code
if (a != null || b != null) {
        if (a == null) {
            val c: Any = b!!
        }
    }
c
The logic behind why it’s not working is a bit weird, but the first if-statement would short-circuit if a is non-null and never evaluate the
b != 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.
k
Thanks, that's interesting. I can't remove the extra if-statement because the actual structure I was working with was more like:
Copy code
val 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...
    }
c
Hmm, I guess you’re right. Either way, though, nested if-statements can be rewritten in a way that keeps them all as a single flat chain of blocks, which is usually much easier to read. Nesting ifs inside ifs quickly gets very difficult to read and trace the logic, especially as the number of variables increases. A when statement like this can be a good way to model the individual conditions of complex logic:
Copy code
when {
    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 */ }
}
d
Actually I think it's possible to add such smartcasts K2 data flow engine smart enough to operate such constructions @Klitos Kyriacou could you please file a feature request to youtrack?
k