Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a getter that takes arguments in Dart

Tags:

getter

dart

I would like to define a getter that can optionally take arguments. I managed to achieve that, however it only works if I put the obligatory () after the call. Here's the code:

get children => ([role=null]) {
  if(role == null || role == 'any') { return _children;               }
  else                              { return _children_by_role[role]; }
};

So now I can say

obj.children('something').length;

or

obj.children().length;

but I cannot say

obj.children; // this doesn't work

because it results in the following error:

Caught Closure call with mismatched arguments: function 'length' NoSuchMethodError : method not found: 'length' Receiver: Closure: ([dynamic])
like image 413
snitko Avatar asked Jan 03 '14 18:01

snitko


1 Answers

In Dart, getters are meant to be indistinguishable from accessing object properties, so it is illegal to define a getter that accepts an argument (even if it's optional).

Your getter takes no arguments, but with the => operator, returns an anonymous function that takes an optional argument. So, obj.children is a function; therefore the statement obj.children.length; is an error because functions don't have the property length.

You may not be able to omit the parentheses, but your code would work more naturally if get children wasn't a getter function:

getChildren([roll]) { // null is the default value implicitly
  if (roll == null || roll == 'any') return _children;
  else return _children_by_roll[roll];
}

used as:

obj.getChildren().length;

or:

obj.getChildren(rollObject).length;
like image 95
Ganymede Avatar answered Oct 17 '22 09:10

Ganymede