How to use optional arguments in defprotocol?

I want to have a function in my type that takes an optional argument. I have successfully used optional arguments in functions that are not of type, however I cannot get it to work in protocol and type.

My failed test:

Clojure 1.4.0 user=> (defprotocol OptArg (func [this a & b])) OptArg user=> (deftype Imp [] OptArg (func [this a & b] (println ab))) user.Imp user=> (func (Imp.) 1 2) CompilerException java.lang.IllegalArgumentException: No single method: func of interface: user.OptArg found for function: func of protocol: OptArg, compiling:(NO_SOURCE_PATH:5) user=> (defn opt-arg [a & b] (println ab)) #'user/opt-arg user=> (opt-arg 1 2) 1 (2) nil user=> (opt-arg 1) 1 nil nil user=> 
+6
source share
2 answers

As answered here , the protocols do not support varargs. You must define a separate method for each required number of arguments, or simply accept the list as an argument.

+8
source

I created defprotocol+ to define a protocol with optional arguments. The idea is to make & args fixed argument in the protocol and automatically create a wrapper function.

Note this meaning for the macro.

Using

  (defprotocol + IPipeline
   (run-and-wait [this & args]))

 (defrecord + Pipeline []
   Ipipeline
   (run-and-wait [this & args]
     )))

 (run-and-wait (Pipeline.) 1 2 3 4 5)

+2
source

Source: https://habr.com/ru/post/915877/


All Articles