Hi guys, is this some compiler bug? With the code ...
# announcements
t
Hi guys, is this some compiler bug? With the code https://hasteb.in/tosejohu.kotlin, the node.left and node.right are not automatically casted as thecorrect types, even though the if statement checks, and we can see from the docs that it technicaly should. https://kotlinlang.org/docs/reference/typecasts.html
var local variables - if the variable is not modified between the check and the usage, is not captured in a lambda that modifies it, and is not a local delegated property;
k
The segment from the doc you quote is about smartcasting the
var
itself, not its properties. Right below that it says:
var properties - never (because the variable can be modified at any time by other code).
s
it’s a local var though, and smartcasting works at least at the top level (of those nodes)
k
Yeah I agree that it's weird, but at least it matches the docs simple smile
s
Copy code
fun test() {
    var node = createBin()

    if (node is BinaryOp) {
        var left = node.left
        var right = node.right
        if (left is IntLit && right is IntLit) {
            right.token.value // unresolved reference: value
            val right = node.right as IntLit
            right.token.value // no problem
        }
    }
}
this works, and I feel like it shouldn’t if that were the case
t
i also saw that, but if that is talking about vars in local contexts too, it is contradictory
s
Hmmm… this works:
Copy code
if(node is BinaryOp) {
        val l = node.left
        val r = node.right
        if(l is IntLit && r is IntLit) {
            r.token.value 
            l.token.value 
        }        
    }
k
@Shawn That just compiles for me fine, what is that comment about?
t
i think he left the comment in the snippet from my example
👆 1
k
@streetsofboston Of course if you explicitly create temporary vars you're in the local var case again which indeed works.
s
@Timothy Wong yeah, my b
My point is that if smartcasting works on that top node item, smartcasting should apply to its children members too
s
Yep, exactly… whether you put
node.left
(and same for
node.right
) in a temporary variable
l
or not should not matter….