Dynamic Polymorphism
Protocols allow defining an abstract set of functions that can be implemented by a concrete type. Let’s look at an example protocol:
| (defprotocol Foo |
| "Foo doc string" |
| (bar [this b] "bar doc string") |
| (baz [this] [this b] "baz doc string")) |
As you can see, the Foo protocol specifies two methods, bar and baz. The first argument to the method will be the object instance followed by its parameters. Note that the baz method has multiple arity. We can now create a type that implements the Foo protocol using the deftype macro:
| (deftype Bar [data] |
| Foo |
| (bar [this param] (println data param)) |
| (baz [this] (println (class this))) |
| (baz [this param] (println param))) |
There we create type Bar that implements ...
Get Web Development with Clojure now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.