(defprotocol IAnimal "IAnimal"
(report [o]
(println (type o) " reporting.\n")
(inner-report o)
(println (type o) " out.\n")))
(defrecord Dog [] IAnimal
(inner-report [o]
(println "Woof Woof.\n")))
(defrecord Cat [] IAnimal
(inner-report [o]
(println "Meow Meow.\n")))
(defrecord Vampire [] IAnimal
(inner-report [o]
(println "I don't sparkle.\n")))
现在,我希望它输出:
Dog reporting.
Woof Woof.
Dog out.
Cat reporting.
Meow Meow.
Cat out.
Vampire reporting.
I don't sparkle.
Vampire out.
不幸的是,这不会发生,因为上面的代码无法编译。实现“这个”的最佳方法是什么?
我所说的“这个”是指我有一些函数想要成为协议的一部分,我想要为所有记录提供一个它的实现,并且我希望这个函数能够访问记录实现的专门函数。
(clojure 的方法是什么?)
协议就像 Java 接口,它们不能提供其方法的实现。但这有效:
(defn report [o]
(println (type o) " reporting.\n")
(inner-report o)
(println (type o) " out.\n"))
(defprotocol IAnimal
"the animal protocol"
(inner-report [o] "a report"))
(defrecord Dog []
IAnimal
(inner-report [o]
(println "Woof Woof.\n")))
(defrecord Cat []
IAnimal
(inner-report [o]
(println "Meow Meow.\n")))
(defrecord Vampire []
IAnimal
(inner-report [o]
(println "I don't sparkle.\n")))
(report (new Cat))
;; user.Cat reporting.
;; Meow Meow.
;; user.Cat out.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)