fromFunction<R> static method

VarArgsFunction<R> fromFunction<R>(
  1. Function function
)

Factory constructor to create a VarArgsFunction from a standard Dart function.

This allows easy conversion of regular functions to VarArgsFunction:

int add(int a, int b) => a + b;
var varAdd = VarArgsFunction.fromFunction(add);
print(varAdd(5, 3)); // Outputs: 8
print(varAdd([5, 3])); // Also works: 8

Implementation

static VarArgsFunction<R> fromFunction<R>(Function function) {
  return VarArgsFunction<R>((args, kwargs) {
    // Process args to handle both direct arguments and list arguments
    List<dynamic> processedArgs;

    if (args.length == 1 && args.first is List) {
      // If the first argument is a list, use it as the arguments list
      processedArgs = args.first;
    } else {
      // Otherwise use the args directly
      processedArgs = args;
    }

    // Use reflection to call the function with the provided arguments
    return Function.apply(function, processedArgs,
        kwargs.map((key, value) => MapEntry(Symbol(key), value)));
  });
}