Erik
Erik

Reputation: 1254

Dart final functions

Is it possible for the _distance variable to be final but still keep the type signatures in the constructor for a Dart object?

Function _distance;

ExampleConstuctor(num distanceFunction(T a, T b)) {
  _distance = distanceFunction;
}

Upvotes: 2

Views: 2345

Answers (3)

Erik
Erik

Reputation: 1254

In addition to the above answers, I also found this works:

class ExampleConstructor<T> {
  final Function _distance;

  ExampleConstructor(num this._distance(T a, T b)) 
}

Upvotes: 2

matanlurey
matanlurey

Reputation: 8614

In 1.24.0, we are introducing a new syntax to do exactly this:

https://github.com/dart-lang/sdk/blob/master/CHANGELOG.md#language-1

typedef F = void Function();  // F is the name for a `void` callback.
int Function(int) f;  // A field `f` that contains an int->int function.

class A<T> {
  // The parameter `callback` is a function that takes a `T` and returns
  // `void`.
  void forEach(void Function(T) callback);
}

// The new function type supports generic arguments.
typedef Invoker = T Function<T>(T Function() callback);

Until then you could also use various typedefs declared in package:func:

https://pub.dartlang.org/packages/func

Upvotes: 4

Harry Terkelsen
Harry Terkelsen

Reputation: 2714

You can use a typedef:

typedef num DistanceFunction<T>(T a, T b);

class ExampleConstructor<T> {
  final DistanceFunction<T> _distance;

  ExampleConstructor(this._distance);
}

Upvotes: 2

Related Questions