closure
カウンターを「インライン化」するメカニズムを使用できます。
(let [c (atom 0)]
(defn new-connection []
{:id (swap! c inc)
:writebuf :ByteBuffer
:readbuf :ByteBuffer})
(defn get-counter []
@c))
(get-counter)
=> 0
(new-connection)
=> {:id 1, :writebuf :ByteBuffer, :readbuf :ByteBuffer}
(new-connection)
=> {:id 2, :writebuf :ByteBuffer, :readbuf :ByteBuffer}
(get-counter)
=> 2
または、カウンターの開始値を制御する必要がある場合:
(defn create-connection-fn [init-counter-value]
(let [c (atom init-counter-value)]
(fn []
{:id (swap! c inc)
:writebuf :ByteBuffer
:readbuf :ByteBuffer})))
(def new-connection (create-connection-fn 10))
(new-connection)
=> {:id 11, :writebuf :ByteBuffer, :readbuf :ByteBuffer}
(new-connection)
=> {:id 12, :writebuf :ByteBuffer, :readbuf :ByteBuffer}
編集。カウンタを「非表示」にする理由がない場合は、カウンタを分離変数として定義することをお勧めします。