Pergunta

In Dart Editor build 27025, the following code produces a syntax error on the line declaring the getter get x:

main() {
  var _x;
  set x(x) => _x = x; // This is okay
  get x => _x;        // Syntax error here
}

Note that the setter set x doesn't produce an error. Is this a bug in Dart Editor or am I doing something wrong here?

Foi útil?

Solução

As you said, getters are functions that are used to retrieve the values of object properties and setters are functions that are used to set the values of object properties. In you example code, _x is not an object property.

The spec shows that getterSignature and setterSignature are only allowed in classes and at the top-level of libraries.

The only thing that surprises me is that your set doesn't produce a syntax error.

Outras dicas

That's an interesting one. I think the bug may be that it doesn't complain about the setter. If you delete the getter and just use the setter it doesn't actually run. Or even parse. Which I think means they're not allowed within a function, though it's not immediately clear to me why.

A Dart project member responded to my bug report that "it isn't valid to declare a getter or a setter inside another method or function. This can be seen by following the grammar for a statement to a localFunctionDeclaration to a functionSignature.

That said, it's a bug that there was no syntax error for the setter."

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top