1

Context: let's create a percent encoder. So, characters will be encoded to theirs % representations. Also, I would like vector of string will be encoded like this: [a b] -> (str (encode a) "+" (encode b)). The reason behind is I want spaces be encoded to %20 for strings and lists of strings cat-ed with +. I made this using protocols:

(defprotocol IUrlEncodable
  (^String url-encode [v]))

(extend-protocol IUrlEncodable
  String
  ;; Do I need type here? I have it in the protocol.
  (^String url-encode [v]
    (-> v URLEncoder/encode (.replace "+" "%20")))
  IPersistentVector
  ;; Same question here.
  (^String url-encode [v]
    (->> v (map url-encode) (join "+"))))

Is it a canonical way to do it? Did I made right thing? What are alternatives? Do I need to redeclare type hint in protocol extension, if I have declared it in the protocol?

1 Answer 1

3

Only the type hint on the protocol function matters; the type hints in method implementations have no purpose. Strictly speaking, the compiler will use type hints attached to Vars holding functions. The var in question here -- #'url-encode -- is created by the defprotocol form (along with #'IUrlEncodable, which holds some protocol administrativia, and a related JVM interface). Metadata attached to the url-encode method name will be transferred to this Var. Metadata attached to symbols naming this method in calls to extend & Co. has no relevance.

Note that technically you don't need any type hints at all, though if you do put them in, they may help the compiler to avoid reflection in some scenarios.

Sign up to request clarification or add additional context in comments.

4 Comments

No, the type hint attached to url-encode as in the function text gets attached to the #'url-encode Var and is interpreted as pertaining to the return values. Type hints attached to arguments are a different matter -- these actually need to be specified in the implementations. (NB. no type hint should be specified on the leading "this" argument, since its type is known.)
(The above was in answer to a comment which was apparently deleted. The question was whether the type hint applies to the parameter v as opposed to the function url-encode.)
Overall, is my code idiomatic? I mean is protocol suitable here?
Yes, using a protocol is fine. Though if you only care about strings and vectors of strings, a simple function with a vector? check would do just as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.