在"Clojure的喜悦"一书中,defprotocol提供了表达式问题的解决方案- "希望为现有的具体类实现一组现有的抽象方法,而不必更改定义任何一个的代码."
给出的例子如下:
(defprotocol Concatenatable
(cat [this other]))
(extend-type String
Concatenatable
(cat [this other]
(.concat this other)))
(cat "House" " of Leaves")
;=> "House of Leaves"
(extend-type java.util.List
Concatenatable
(cat [this other]
(concat this other)))
(cat [1 2 3] [4 5 6])
;=> (1 2 3 4 5 6)
Run Code Online (Sandbox Code Playgroud)
有人认为这在Java这样的语言中是不可能的,但它与以下内容有何不同?
public class Util {
public static String cat(final String first,
final String second) {
return first.concat(second);
}
public static <T> List<T> cat(final List<T> first,
final List<T> …Run Code Online (Sandbox Code Playgroud)