Function overloading in Dart

Calebe picture Calebe · Apr 9, 2018 · Viewed 13.8k times · Source

The following code:

class Tools {
  static int roll(int min, int max) {
    // IMPLEMENTATION
  }

  static int roll(List<int> pair) {
    // IMPLEMENTATION
  }
}

renders a The name 'roll' is already defined error on the second roll function.

How come? Since the parameters of the functions are distinct, shouldn't polymorphism apply?

Edit. Corrected title in order to better reflect the subject.

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Apr 9, 2018

What your code demonstrates is function overloading and not related to polymorphism.

Function overloading is not supported in Dart at all.

You can either use different names for the methods or optional named or unnamed parameters

// optional unnamed
void foo(int a, [String b]);
...
foo(5);
foo(5, 'bar');

// optional named
void foo(int a, {String b});
...
foo(5);
foo(5, b :'bar');

Optional parameters can also have default values. Optional named and unnamed parameters can not be used toghether (only one or the other for a single function)

Polymorphism and static methods:

Static methods can only be accessed without the class name as prefix from inside the class where they are defined. When called from subclasses, the name of the superclass needs to be used as prefix.