O'Reilly logo

Web Development with Clojure by Dmitri Sotnikov

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required