Does dart support operator overloading

Muhammad Umer picture Muhammad Umer · Apr 12, 2012 · Viewed 11.4k times · Source

I read that Dart does not support function overloading. Does it support operator overloading. If yes, would be kind and show me how in a simple example how its done. And what are some advantages etc. I am new to programming. Thanks.

Answer

Lars Tackmann picture Lars Tackmann · Apr 12, 2012

Dart does support operator overloading using the operator keyword followed by the operator you want to overload. The following example overloads the == operator for the MyClass object:

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

almost all Darts built-in operators can be overloaded with a few notable exceptions being the assignment operator = and reference equivalence operator === (doesn't exist anymore).

As for the advantage of operator overloading, it allows you to reuse operators that have a well known semantic meaning such as == or + for operations on your objects. For example, if you have a Matrix class that overloads the + operator then you can add two matrices using the syntax m1 + m2 instead of the more cumbersome m1.plus(m2)