Home > OS >  access arguments similar to this.variable
access arguments similar to this.variable

Time:05-12

void main() {
  doStuff("foo");
}

void doStuff(String myString) {
  String myString = "bar";
  print(myString); //prints "bar"
}

The above executed in the dartpad yields "bar", the local variable is used instead of the parameter in the last line. If instead of an argument myString were an instance variable of a class, we could access the original myString with this.myString to print "foo". Is there an analogous way to access an argument to a function after a homonymous local variable has been declared?

CodePudding user response:

No.

For local variables, you are expected to be able to rename any local variable which shadows the variable you want to access, so there is no scope override.

For instance variables, you can use this.x, for static variables you can use ClassName.x, for an imported top-level name, you can import the library with a fresh prefix name and access it as prefix.x, and for public top-level variable of the current library, you can, if all else fails, import that library with a prefix too and use:

// library foo.dart
import "foo.dart" as toplevel; // <- this library!
// ...
int foo = 42;
// ...
int method(int foo) {
 return toplevel.foo   foo; // Wohoo

For local variables, you just have to rename the one that's shadowing the variable you want. Since nobody can see local variables from outside the method, no-one will ever know.

  •  Tags:  
  • dart
  • Related