functionoverloadingoperator-keyworddart

Does dart support operator overloading


I read that Dart does not support function overloading. Does it support operator overloading? If yes, can you show me how it's done in a simple example? And what are some advantages etc?


Solution

  • The chosen answer is no longer valid when you try overloads using the == operator in the new version. Now you need to do this:

    class MyClass {
      @override
      bool operator ==(other) {
        // compare this to other
      }
    }
    

    But it's not safe. other is not specified as a type, Something unexpected may happened. For example:

    void main() {
      var a = A(1);
      var b = B(1);
      var result = a == b;
      print(result); //result is true
    }
    
    class A {
      A(this.index);
    
      final int index;
    
      @override
      bool operator ==(other) => other.index == index;
    }
    
    class B {
      B(this.index);
    
      final int index;
    }
    

    So you could do like this:

    class A {
      A(this.index);
    
      final int index;
    
      @override
      bool operator ==(covariant A other) => other.index == index;
    }
    

    You need to use covariant. Because Object overloads the == operator.

    or you can

    Test Object Type:
    visit: hash_and_equals

    class A {
      A(this.index);
    
      final int index;
    
      @override
      bool operator ==(other) => other is A && (other.index == index);
    
      @override
      int get hashCode => index;
    }