Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with the following Clojure protocol?

In Clojure 1.2:

(defprotocol PP 
  (foo [bar]) 
  (foo [bar baz]))
=> PP

(extend-protocol PP 
  Object 
    (foo [bar] 1) 
    (foo [bar baz] 2))
=> nil

(foo "hello!")
=> #<CompilerException java.lang.IllegalArgumentException: No single method: foo of interface: PP found for function: foo of protocol: PP

Where am I going wrong? I'd expect to see 1 as the result from the single-argument version of the foo function, since "hello!" is clearly an instance of java.lang.Object.

like image 903
mikera Avatar asked Feb 03 '11 22:02

mikera


1 Answers

I think the second foo in your protocol is clobbering the first one. Overloading on arity has slightly different syntax than you're using.

user> (defprotocol PP
        (foo [bar] [bar baz]))
PP
user> (extend-protocol PP
        Object
        (foo 
          ([bar] 1)
          ([bar baz] 2)))
nil
user> (foo "foo")
1
user> (foo "foo" "bar")
2
like image 138
Brian Carper Avatar answered Nov 12 '22 20:11

Brian Carper