初始化 Java 对象的 Clojure 惯用方法
我正在尝试找到一种 Clojure 惯用的方法来初始化 Java 对象。我有以下代码:
(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
)
但看起来非常尴尬。
创建 HttpURLConnection 对象并在稍后在代码中使用它之前对其进行初始化的更好方法是什么?
更新:似乎 (doto ...)
在这里可能会派上用场:
(let [url-connection
(doto (java.net.HttpURLConnection.)
(.setDoInput true)
; more initialization
))]
; use the url-connection
)
根据 doto
文档,它返回的值是它是“做”。
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".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如我的问题更新中所解释的,这是我得出的答案:
也许有人可以想出更好的答案。
As explained in the update to my question, here is the answer I came up with:
Maybe someone can come up with a better one.
假设没有构造函数接受所需的所有初始化参数,那么您的做法是我所知道的唯一一种。
您可以做的一件事是将其全部包装在这样的函数中:
并调用:
但是,这是每个对象特定的,并且仅当您多次初始化该类的对象时它才真正有用。
您还可以编写一个接受所有方法名称和参数的宏并执行此操作。但是,当调用时,该调用不会比您的第一个示例短很多。
如果有人有更好的主意,我想看看,因为前几天我也问自己同样的问题。
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:
And call with:
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..