(defprotocol Connectable
(my-cat [this other]))
=> Connectable
#_ 扩展 List 类型
(extend-type java.util.List
Connectable
(my-cat [this other]
(println "List my-cat")
(concat this other)))
=> nil
(my-cat [1 2 3] [4 5 6])
List my-cat
=> (1 2 3 4 5 6)
#_ 扩展 String 类型
(extend-type String
Connectable
(my-cat [this other]
(println "String my-cat")
(.concat this other)))
=> nil
(my-cat "1231" "213123")
String my-cat
=> "1231213123"
表达式问题
指在不修改已定义代码的前提下,为既有具体类实现一套既有的抽象方法。
Clojure 的协议可以扩展到任何有意义的类型上。甚至是类型实现者或者协议实现者都没想过的地方。
引自《Clojure编程乐趣 第二版》