接口继承

类 / 继承

(defprotocol Shape
  (area [this]))

(defrecord Square [side])

;; extend-type 正是从外部把协议附加到类型上,
;; 而且可以在类型本身写成很久之后
(extend-type Square
  Shape
  (area [this] (let [s (:side this)] (* s s))))

;; 它甚至适用于不属于自己的类型,哪怕是 String,
;; 任何基于类的语言都不允许扩展它
(extend-type String
  Shape
  (area [this] (count this)))

(println "area is" (area (->Square 5)))
(println "area is" (area "hello"))