Web Technology Digital Transformation Technology. Artificial Intelligence Technology Natural Language Processing Technology Semantic Web Technology Deep Learning Technology Online Learning & Reinforcement Learning Technology Chatbot and Q&A Technology User Interface Technology Knowledge Information Processing Technology Reasoning Technology Clojure Programming
There are two functions for handling classes in Clojure: defrecord and deftype. deftype has a use for handling mutable variables. I will summarize them below. First, the pattern using definterface.
(definterface IPoint
(getX [])
(setX [v]))
(deftype Point [x]
IPoint
(getX [this] x)
(setX [this v] (set! (.x this) v)))
(def p (Point. 10))
(.getX p)
;;-> 10
(.setX p 20)
;;->20
(.getX p)
;;->20
In the old sample, the setting of “x” in the deftype was “[^{:volatile-mutable true} x]” and it was said that it did not work unless it was set as a mutable variable.
The following is an example of using defprotocol.
(defprotocol IPoint2
(getX [this])
(setX [this val]))
(deftype Point2 [^{:volatile-mutable true} x]
IPoint2
(getX [_] x)
(setX [this v] (set! x v)))
(def p2 (Point. 10))
(.getX p2)
;;-> 10
(.setX p2 20)
;;->20
(.getX p2)
;;->20
It works in the same way. Finally, we show an example of setting multiple protocols.
(defprotocol IPoint3
(getX1 [this])
(setX1 [this val])
(getX2 [this])
(setX2 [this val]))
(deftype Point3 [^{:volatile-mutable true} x
^{:volatile-mutable true} y]
IPoint3
(getX1 [_] x)
(setX1 [this v] (set! x v))
(getX2 [_] y)
(setX2 [this v] (set! y v)))
(def p3 (Point3. 10 20))
(.getX1 p3)
;;-> 10
(.setX1 p3 "hello")
;;->"hello"
(.getX1 p3)
;;-> "hello"
This means that mutable class data can be constructed.
コメント