Declare Member Variables with gen-class in Clojure

前端 未结 3 603
盖世英雄少女心
盖世英雄少女心 2021-01-13 20:49

I\'m learning how to extend Java classes in Clojure, but I don\'t see a way declare new member variables; I only see a way for methods.

(ns test.aclass
  (:g         


        
3条回答
  •  悲&欢浪女
    2021-01-13 20:54

    The body of a proxy is a lexical closure, so you can just close around whatever variables you need. If, God forbid, you need to mutate them, then close around an atom:

    (defn lying-list [init-size]
      (let [the-size (atom init-size)]
        (proxy [java.util.ArrayList] []
          (size [] @the-size)
          (remove [idx] (reset! the-size idx), true))))
    

    There's really no need for actual Java fields here.

提交回复
热议问题