Search code examples
polymorphismlanguage-designlanguage-featureshacklang

Will Hack language support function-overloading polymorphism?


I was trying to figure out how to implement a Visitor pattern in Hack. It obviously requires function-overloading polymorhism, but as I have tested, this examle:

<?hh // strict
class Visitor {
    public function visit(string $s) : void {}
    public function visit(int $i) : void {}
}

produces the usual PHP's

Fatal error: Redeclared method Visitor::visit in hh-polymorphism.php on line 4

And since this failed, then I would like to ask if there are plans to support this in future? Or are there any factors that would prevent this from being implemented?


Solution

  • We almost certainly will not be able to have overloading in Hack, as I explained in this feature request. You can see there for a detailed answer, but the crux of the issue is that it would totally break interoperability with vanilla PHP, or even partial mode -- you need full type information in order to actually resolve the overload, which we can't promise we have except in 100% strict mode. (There are other reasons too, see that link.)

    For your example, you can always do something like this, taking advantage of mixed and Hack's flow sensitivity:

    <?hh // strict
    class Visitor {
      public function visitString(string $s): void {
        // ...
      }
      public function visitInt(int $i): void {
        // ...
      }
      public function visit(mixed $m): void {
        if (is_int($m)) {
          $this->visitInt($m);
        } else if (is_string($m)) {
          $this->visitString($m);
        } else if (...) {
          ...
        } else {
           invariant_violation('Unexpected type in visitor: %s', gettype($m));
        }
      }
    }