A dispatch function is the decision point inside a multimethod: it defines the callable signature, validates arguments, and emits the value used to select an implementation. The same arguments then flow to both the dispatch function and the selected method. section 13.2 section 13.6
A useful dispatch function handles three jobs:
- Define which arguments the multimethod accepts. section 13.6
- Validate those arguments, typically during development. section 13.2 section 13.3
- Emit a dispatch value, such as an animal type, a tuple of types, or a type-and-Boolean combination. section 13.2 section 13.4
From one animal to two decisions
For single dispatch, greetDispatch(animal) validates an animal map and returns animal.type, sending dogs, cats, and cows to different methods. For multiple dispatch, greetLangDispatch(animal, language) returns [animal.type, language.type], so a dog speaking French reaches a different implementation from the same dog speaking English. Dynamic dispatch goes further: dysGreetDispatch returns [animal.type, animal.name.length > 5], allowing behavior to depend on a runtime property rather than only a type. section 13.2 section 13.3 section 13.4
Listing 13.6 The dispatch function for greet multimethod
function greetDispatch(animal) { #1
if(dev()) {
if(!ajv.validate(animalSchema, animal)) { #2
var errors = ajv.errorsText(ajv.errors);
throw ("greet called with invalid arguments: " + errors);
}
}
return animal.type; #3
}
var greet = multi(greetDispatch); #4
Inspect the complete single-dispatch function, including development-time validation, the emitted animal type, and multimethod initialization. section 13.2
Listing 13.15 Initializing a multimethod with a dispatch function
var greetLangArgsSchema = {
"type": "array",
"prefixItems": [animalSchema, languageSchema]
};
function greetLangDispatch(animal, language) {
if(dev()) {
if(!ajv.validate(greetLangArgsSchema, [animal, language])) {
throw ("greetLang called with invalid arguments: " +
ajv.errorsText(ajv.errors));
}
}
return [animal.type, language.type];
};
var greetLang = multi(greetLangDispatch);
Compare a two-argument signature with validation and an array-valued dispatch result. section 13.3
Listing 13.18 A multimethod using a dispatch function with dynamic dispatch
function dysGreetDispatch(animal) {
if(dev()) {
if(!ajv.validate(animalSchema, animal)) {
var errors = ajv.errorsText(ajv.errors);
throw ("dysGreet called with invalid arguments: " + errors);
}
}
var hasLongName = animal.name.length > 5;
return [animal.type, hasLongName];
};
var dysGreet = multi(dysGreetDispatch);
See dynamic dispatch turn a name-length test into part of the method-selection value. section 13.4

