Michel Feinstein
Michel Feinstein

Reputation: 14296

Dart name collision resolution

I have a file in Dart that looks like this:

library myLibrary;

bool myFunction(String s) => s == null;

extension StringExtensions on String {
  bool get myFunction=> myFunction(this);
}

Where I basically want to add extensions to previous existing functions, with the same name.

The Dart compiler complains about this, as it can't see the outer myFunction() name, just the getter, inside StringExtensions.

Is it there a way for me to reference the external myFunction from inside StringExtensions? Or can I just achieve this by separatting them in two different files/libraries using aliases?

Upvotes: 2

Views: 514

Answers (2)

Michel Feinstein
Michel Feinstein

Reputation: 14296

We can import the file itself with an alias:

library myLibrary;

// file: my_library.dart
import "my_library.dart" as prefix;

bool myFunction(String s) => s == null;

extension StringExtensions on String {
  bool get myFunction=> prefix.myFunction(this);
}

As shown here.

Upvotes: 0

smac89
smac89

Reputation: 43196

You could create a private reference to the function and use that inside your extension:

final _myFunction = myFunction;
extension StringExtensions on String {
  bool get myFunction => _myFunction(this);
}

In order to avoid the overhead of creating private references, you can just create a new file for the extensions and import myLibrary using an alias:

import 'package:myLibrary/myLibrary.dart' as myLibray;

extension StringExtensions on String {
  bool get myFunction => myLibrary.myFunction(this);
}

...

Upvotes: 3

Related Questions