Human-Powered Random Text Generator

Random thoughts by Yu Asakusa

Variadic functions in Dart

23 Jan 2014

There is a feature request to support functions which can take a variable number of arguments in Dart (the same request was mentioned earlier in a comment to another feature request). But we can implement such functions without modifying the language or the compiler!

typedef dynamic ApplyType(List positionalArguments);

class Variadic implements Function {
  final ApplyType _apply;

  Variadic(this._apply) {}

  @override
  dynamic noSuchMethod(Invocation invocation) {
    if (invocation.memberName == #call) {
      if (invocation.isMethod)
        return _apply(invocation.positionalArguments);
      if (invocation.isGetter)
        return this;
    }
    return super.noSuchMethod(invocation);
  }
}

num sumList(List<num> xs) =>
  xs.fold(0, (num acc, num x) => acc + x);

final Function sumVariadic = new Variadic(sumList);

void main() {
  print(sumList([100, 200, 300]));
  print(sumVariadic(100, 200, 300));
}

Notes: