Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The goal of dispatching is to dynamically decide what to do in your function.</p> <p>When you have a (dynamic) dispatch function it's main (or only, if you don't need casting or other conversions) responsibility is to decide which other function to call. The decision is often based on the type of the instance the method is called on, or the type of some of the parameters, but it can also depend e.g. on the value of the parameter(s), or some config values. </p> <p>The dispatching rule can be hardcoded (using e.g. pattern matching in scala), or may come from a dispatch table. </p> <p>As you mentioned there are several variations, like single dispatch (concrete method depends on the instance the original method is called on, which is a basic OO mechanism), double dispatch (dispatches a function call to different concrete functions depending on the runtime types of multiple objects involved in the call). </p> <p>A related design pattern is the Visitor, which allows you to add a set of functions dynamically to existing classes and which also has dynamic dispatch at its core.</p> <p>The nested blocks/closures appear when you define the concrete method inside of the dispatch method, or in some initialization code (e.f. for the dispatch table).</p> <p>A simple example for the case when dispatching is based on the value of the parameter, with hardcoded decision and with dispatch table:</p> <pre><code> class Dispatch { def helloJohn(): String = "Hello John" def helloJoe(): String = "Hello Joe" def helloOthers(): String = "Hello" def sayHello(msg: String): String = msg match { case "John" =&gt; helloJohn() case "Joe" =&gt; helloJoe() case _ =&gt; helloOthers() } val fs = Map("John" -&gt; helloJohn _, "Joe" -&gt; helloJoe _) def sayHelloDispatchTable(msg: String): String = fs.get(msg) match { case Some(f) =&gt; f() case _ =&gt; helloOthers() } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload