https://kotlinlang.org logo
#announcements
Title
# announcements
t

Timothy Wong

06/28/2019, 7:08 PM
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

karelpeeters

06/28/2019, 7:12 PM
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

Shawn

06/28/2019, 7:14 PM
it’s a local var though, and smartcasting works at least at the top level (of those nodes)
k

karelpeeters

06/28/2019, 7:15 PM
Yeah I agree that it's weird, but at least it matches the docs simple smile
s

Shawn

06/28/2019, 7:15 PM
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

Timothy Wong

06/28/2019, 7:15 PM
i also saw that, but if that is talking about vars in local contexts too, it is contradictory
s

streetsofboston

06/28/2019, 7:16 PM
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

karelpeeters

06/28/2019, 7:19 PM
@Shawn That just compiles for me fine, what is that comment about?
t

Timothy Wong

06/28/2019, 7:20 PM
i think he left the comment in the snippet from my example
👆 1
k

karelpeeters

06/28/2019, 7:20 PM
@streetsofboston Of course if you explicitly create temporary vars you're in the local var case again which indeed works.
s

Shawn

06/28/2019, 7:20 PM
@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

streetsofboston

06/28/2019, 7:24 PM
Yep, exactly… whether you put
node.left
(and same for
node.right
) in a temporary variable
l
or not should not matter….