13 Polymorphism

 

Playing with the animals in the countryside

Hidden listing
window.dev = function () {
  return true;
}
class Author {}
window.Author = Author;

function KlipseLoadLib(url, symbol) {
  if (window[symbol]) {
    return;
  }
  var script = document.createElement('script');
  script.src = url;
  document.body.append(script);
}
KlipseLoadLib("https://viebel.github.io/klipse/repo/js/multimethod.js", "multimethod");
var {multi, method, fromMulti} = window.multimethod;
KlipseLoadLib("https://cdnjs.cloudflare.com/ajax/libs/ajv/6.12.6/ajv.bundle.js", "Ajv");
window.ajv = new Ajv();

This chapter covers

  • Mimicking objects with multimethods (single dispatch)
  • Implementing multimethod on several argument types (multiple dispatch)
  • Implementing multimethods dynamically on several arguments (dynamic dispatch)

OOP is well-known for allowing different classes to be called with the same interface via a mechanism called polymorphism. It may seem that the only way to have polymorphism in a program is with objects. In fact, in this chapter, we are going to see that it is possible to have polymorphism without objects, thanks to multimethods. Moreover, multimethods provide a more advanced polymorphism than OOP polymorphism because they support cases where the chosen implementation depends on several argument types (multiple dispatch) and even on the dynamic value of the arguments (dynamic dispatch).

13.1 The essence of polymorphism

13.2 Multimethods with single dispatch

13.3 Multimethods with multiple dispatch

13.4 Multimethods with dynamic dispatch

13.5 Integrating multimethods in a production system

Summary