Clojure-idiomatic way to initialize a Java object

一笑奈何 提交于 2019-12-08 20:10:51

问题


I am trying to find a Clojure-idiomatic way to initialize a Java object. I have the following code:

(let [url-connection
      (let [url-conn (java.net.HttpURLConnection.)]
        (doto url-conn
          (.setDoInput true)
          ; more initialization on url-conn
          )
        url-conn)]
  ; use the url-connection
  )

but it seems very awkward.

What is a better way to create the HttpURLConnection object and initialize it before using it later in the code?

UPDATE: It seems that (doto ...) may come in handy here:

(let [url-connection
        (doto (java.net.HttpURLConnection.)
          (.setDoInput true)
          ; more initialization
          ))]
  ; use the url-connection
  )

According to the doto docs, it returns the value to which it is "doing".


回答1:


As explained in the update to my question, here is the answer I came up with:

(let [url-connection
        (doto (java.net.HttpURLConnection.)
          (.setDoInput true)
          ; more initialization
          ))]
  ; use the url-connection
  )

Maybe someone can come up with a better one.




回答2:


Assuming that there is no constructor that accepts all the initialization parameters needed, then the way you did it is the only one I know.

The one thing you could do is wrap it all in a function like this:

(defn init-url-conn [doInput ...other params..] 
     (let [url-conn (java.net.HttpURLConnection.)]
        (doto url-conn
          (.setDoInput true)
          ; more initialization on url-conn
          )
        url-conn))

And call with:

(let [url-connection
      (let [url-conn (init-url-con true ...other params..)]
  ; use the url-connection
  )

However, this is specific per object and it is really useful only if you are initializing object of that class more than once.

Also you could write a macro that accepts all method names, and params and does this. But, when called, that call wouldn't be much shorter than your first example.

If anyone has a better idea, I'd like to see it, since I was asking myself the same just the other day..



来源:https://stackoverflow.com/questions/4314718/clojure-idiomatic-way-to-initialize-a-java-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!