Language: Access to top-level variables which would be shadowed by local variables

Created on 14 Jan 2020  路  3Comments  路  Source: dart-lang/language

For null safety, Dart takes a strategy of smart promotion with assignment analysis. It works well for local variable, but for some complicated reasons, instance variables can't be type promoted. So, for the sake of type promotion, assigning a instance variable to a local variable is decent practice, such as

var a = this.a;
if(a != null){
  print(a + 1);
}

A local variables with distinct name such as var b = a; // this.a might be better, but from the view point of migration, same name as instance variable is reasonable.

For top-level variables, however, we can't take the same practice, because top-level variables which would be shadowed by local variables don't have a way to be accessed.

Now, I would like to propose special identifier top or like in order to access top level variables which would be shadowed by local ones, such as

var a = top.a;
if(a != null){
  print(a + 1);
}
feature

Most helpful comment

You can do this (but only with a bleeding-edge tool, so you have to wait a bit in order to get support for it everywhere):

import '' as top;

var foo = 1;

void main() {
  var foo = print('');
  top.foo = 2; // Use the prefix `top` to get access to shadowed top level name.
}

The point is that the empty string is a relative reference to the current library.

All 3 comments

You can do this (but only with a bleeding-edge tool, so you have to wait a bit in order to get support for it everywhere):

import '' as top;

var foo = 1;

void main() {
  var foo = print('');
  top.foo = 2; // Use the prefix `top` to get access to shadowed top level name.
}

The point is that the empty string is a relative reference to the current library.

Thank you for your information.

You should also be able to just do:

import 'whatever_this_librarys_name_is.dart' as top;

Most libraries do know their filename, so this should work and should work for any version of the SDK.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

munificent picture munificent  路  5Comments

marcelgarus picture marcelgarus  路  3Comments

jonasfj picture jonasfj  路  3Comments

dev-aentgs picture dev-aentgs  路  3Comments

natebosch picture natebosch  路  4Comments