Skip to content

Proposal implement Function.applyByName to Use Function Name as a String #60350

@insinfo

Description

@insinfo

Context

Currently, the Dart SDK allows the use of Function.apply to invoke functions dynamically by passing positional and named arguments, as shown in the example below:

void printWineDetails(int vintage, {String? country, String? name}) {
  print('Name: $name, Country: $country, Vintage: $vintage');
}

void main() {
  Function.apply(printWineDetails, [2018], {#country: 'USA', #name: 'Dominus Estate'});
}

This method offers flexibility to invoke functions at runtime. However, a feature that could add more dynamism to Dart would be the ability to invoke a function by passing its name as a string. This is useful, for example, when we want to call functions more flexibly, such as in a configuration-based or dynamic execution logic system where the function name is determined at runtime.

Proposal

The proposal is to extend the Function.apply method to allow the function name to be passed as a string, instead of directly providing the function reference in the code. In other words, allow the apply method to accept a string that corresponds to the function's name in the current scope.

Expected Usage Example
Imagine a scenario where we have several functions and want to call them dynamically based on the function name at runtime:

// Defining some functions
void greet() {
  print('Hello, world!');
}

void farewell() {
  print('Goodbye, world!');
}

void printWineDetails(int vintage, {String? country, String? name}) {
  print('Name: $name, Country: $country, Vintage: $vintage');
}

// Calling functions dynamically by name as a string
void main() {
  String functionName = 'greet';  // Function name to be called
  Function.applyByName(functionName, null);  // Calls greet()

  functionName = 'farewell';  // Function name to be called
  Function.applyByName(functionName, null);  // Calls farewell()

  functionName = 'printWineDetails';  // Function name to be called
  Function.applyByName(functionName, [2018], {#country: 'USA', #name: 'Dominus Estate'});  // Calls printWineDetails
}

Expected Benefits

Flexibility: Allowing dynamic function invocation by name makes the code more flexible and adaptable to scenarios where the application's behavior depends on configuration or runtime logic.

Better Support for Frameworks and Tools: This functionality would be useful for testing tools, dependency injection frameworks, or any system that needs to call functions dynamically.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-languageDart language related items (some items might be better tracked at github.com/dart-lang/language).type-enhancementA request for a change that isn't a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions