The ALTernative Language
Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Dynamic dispatch

In this example we show how to dynamically dispatch on values. Essentially, dynamic dispatch is the conditional execution of different pieces of code.

In traditional OO languages, the (receiver) object’s runtime type and the method name determine the condition what code will be executed. In more advanced OO languages, the argument runtime types are also considered, for instance, in languages that implemented multi methods.

Can we do something similar in ALT?

Let’s define a nested struct add that can dispatch on two different ‘object’ types:

  • A single number
  • And a sequence of exactly 2 numbers

Note that this example ’extends’ the complex number example. Also note that you cannot overload a function like that in other languages such as Haskell.