3 ms·
> The Dart compiler knows if I do a null-check, it can treat following references as safe, instead of if let x = x etc. Does Dart bind a new variable 'x' for t
by hgs3 3y ago
> The Dart compiler knows if I do a null-check, it can treat following references as safe, instead of if let x = x etc.
Does Dart bind a new variable 'x' for the if-statement scope or does the if-statement scope refer to the same 'x' from the outer scope?
The reason Swift and other languages bind a new 'x' variable (if let x = x) is because the original 'x' can be assigned a different value elsewhere, like in another thread or a closure. If a closure captures and assigns null to 'x' and there is only one binding of 'x', then that means the 'x' within the if-statement will become null _post null-check_ which is type unsound. I believe TypeScript has this "problem" as well.
- FuturisticGoo 3y agoI assume Dart refers to the same variable since: 1) Dart doesn't have threads, it has isolates (where memory is not shared). So no variable modifications here. 2) Dart will promote a variable as not null after a non-null check only if it cannot be modified elsewhere, ie, the variable is final (can't be modified once assigned), or there's no other reference to it.
- KerrAvon 3y agogentle reminder that `if let x = x` can now be spelled simply `if let x` in current versions of Swift
- jwells89 3y agoHave been loving this feature. It’s a small but impactful QoL improvement.