I really wish there was a way to assure the compil...
# codingconventions
g
I really wish there was a way to assure the compiler that this var will not be changed outside of this scope that way you didn't have to do !! for every call. Like it's a locally scoped var, its not going to get touched by another thread. to be clear - I 100% understand why an if statement vs a ?.let causes no smart cast vs a smart cast, I just wish there was a way you could do !! for an entire scope or something similar. Sure in this specific context of ksoup you could use a for loop and a safe called let, but it's just an example and I need to refer back to the last element for some processing so I can't do a for or a map. Or maybe some sort of loop where you do a snapshot inside. I guess I could write a scope function that does that, but all that does is move the silly while chained let somewhere else haha
s
Have you got an example of something you want to be able to do that doesn't work? An if statements on a locally-scoped
var
should create a smart cast just fine...
r
I always find generateSequence works really well for linked-list type structures:
Copy code
generateSequence (element) {it.nextElementSibling()}
will just give all elements and no nulls and no need for a nullable var
2
k
If you're referring to the line
println(element)
not showing
element
in green, that's because
element
doesn't need to be smart-cast at that point, since
println
is perfectly happy with being passed
null
. But at that point the compiler already knows that
element
is in fact smart-cast nevertheless.
g
No, that was just a quick demo screenshot I took. I'm aware of the print behavior of nulls since it accepts a Any? at no point in that if statement will element be not-nullable, the compiler will not smart cast inside an if statement because theres no snapshot and thus no thread safety. Thats why it works in a safe-called let, but not an if.
Huh, genererateSequence actually looks like it solves this specific problem, thats pretty cool, thanks!
k
at no point in that if statement will element be not-nullable
Which if statement are you referring to? I can only see a
while
statement in your code snippet. Anyway, the only time the compiler will not smart-cast is when the variable is not a local one. For example, if
element
is a property.