Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify a default value of a function parameter?

Tags:

dart

This function should transform each element of the list with the given function transform:

void _doSomething(List<Something> numbers, [transform(Something element)]) {...}

As I don't want to skip this method when the transform should not do anything, I wanted to give a default value to the transform method like this:

void _doSomething(List<Something> numbers, 
                  [transform(Something element) = (v) => v]) {...}

Unfortunately, the editor tells me

Expected constant expected

Is there some workaround or simply not possible (or shouldn't be done like this at all)?

like image 829
Bluenuance Avatar asked Mar 11 '13 09:03

Bluenuance


1 Answers

if you want to initialize a Function parameter that is also a field of your class I suggest:

class MyClass{
  Function myFunc;
  MyClass({this.myFunc = _myDefaultFunc}){...}
  static _myDefaultFunc(){...}
}

Or more suitable:

typedef SpecialFunction = ReturnType Function(
                              FirstParameterType firstParameter, 
                              SecondParameterType secondParameter);

class MyClass{
  SpecialFunction myFunc;
  MyClass({this.myFunc = _myDefaultFunc}){...}
  static ReturnType _myDefaultFunc(FirstParameterType firstParameter, 
                                   SecondParameterType secondParameter){...}
}
like image 53
itai schwed Avatar answered Oct 10 '22 19:10

itai schwed