Freewind
Freewind

Reputation: 198238

Why can't this simple Dart code be compiled?

Here is some simple Dart code:

class P {
  var name = myname();

  String myname() => "PPP";
}

main() {
  new P();
}

It reports this error when running:

Error: line 2 pos 14: illegal implicit access to receiver 'this'
  var name = myname();
             ^

What is causing this error?

Upvotes: 0

Views: 614

Answers (1)

Darshan Rivka Whittle
Darshan Rivka Whittle

Reputation: 34031

You're attempting to evaluate a non-static method in a static context (see note). You can either mark the method as static:

class P {
  var name = myname();

  static String myname() => "PPP";
}

Or evaluate the code in a non-static context:

class P {
  var name;

  P() {name = myname();}

  static String myname() => "PPP";
}

Note: The concept of "static context" here is my mental model, which may or may not perfectly match how Dart works. It may be more correct to note that this simply isn't available in a field initializer, explicitly or implicitly.

Upvotes: 3

Related Questions