Skip to content

New feature wanted #49330

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
seifalmotaz opened this issue Jun 24, 2022 · 2 comments
Closed

New feature wanted #49330

seifalmotaz opened this issue Jun 24, 2022 · 2 comments

Comments

@seifalmotaz
Copy link

Hi.
I know that there is a Function.apply method that works just like the main function.
I have an idea to make a new function let's say Function.prepare that prepare the function to be called then calls the function later.
Example:

void example(String str) {
      print(str)
}

void main() {
      var preparedFunction = Function.prepare(example, ['hello world']);
      //  ... do some code then
      preparedFunction.call(); // or preparedFunction.apply();
}
@julemand101
Copy link
Contributor

How is this different from doing:

void example(String str) {
  print(str);
}

void main() {
  var preparedFunction = () => example('hello world');
  //  ... do some code then
  preparedFunction(); // hello world
}

@natebosch
Copy link
Member

@julemand101 - It's a little different in that Function.apply unwraps a List into the individual arguments. It works to specialize to the argument shape in this example - and that's what I'd do in most cases.

@seifalmotaz - If you do need to handle functions with unknown arity or argument type (I'd avoid this if you can) you can wrap Function.apply. This is not functionality we'll include directly in the SDK.

Object? Function() applyArguments(Function f, List<Object?> args) =>
    () => Function.apply(f, args);

void example(String str) {
  print(str);
}

void main() {
  var preparedFunction = applyArguments(example, ['hello world']);
  //  ... do some code then
  preparedFunction();
}

For more discussion around feature requests fo language level support for partial application, see dart-lang/language#351

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants