Bluenuance
Bluenuance

Reputation: 629

How to specify a default value of a function parameter?

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)?

Upvotes: 25

Views: 18610

Answers (3)

Hypermona
Hypermona

Reputation: 147

Write your default parameters inside a square bracket []

DummyFunctin(String var1, int Var2,[ String var3 = "hello", double var4 = 3.0, List<int> var5 = [2,4,5,6],] ){
// some calculation
// return something
}

DART Cheatsheet For JavaScript or TypeScript Developers

Upvotes: 9

Alexandre Ardhuin
Alexandre Ardhuin

Reputation: 76213

You can define the default function as private method :

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

Or check argument like this :

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

Or like Ladicek suggests :

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

Upvotes: 7

itai schwed
itai schwed

Reputation: 469

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){...}
}

Upvotes: 17

Related Questions