0

I am using mongo java driver along with clojure for mongo connection, to establish connection in java I am using following code snippet

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.ServerAddress;

MongoClientURI uri = new MongoClientURI("mongodb://xxx:***@url:27017/test?readPreference=primary");
List<String> hosts = uri.getHosts();
List<ServerAddress> serverList = new LinkedList<>();

for(String host:hosts) {
    serverList.add(new ServerAddress(host)); //updated
}

I want to get this same functionality in clojure so I tried this

(def uri (MongoClientURI. uri))
(def hosts (.getHosts uri))

Now I have List of hosts which are String, how do I convert them to list of type ServerAddress ?

0

1 Answer 1

2

What's perhaps a little hard to spot in the Java code is that because serverList is a List<ServerAddress>, when you add String objects to that, they are implicitly converted to ServerAddress objects via the latter's constructor.

Something like the following should get you what you want:

(def host (map #(ServerAddress. %) (.getHosts uri)))

Note that you'll have a Clojure sequence at that point -- if you are passing it into Java methods, you may need to type hint it or even pour it into a (mutable) Java List.

Sign up to request clarification or add additional context in comments.

3 Comments

No, the Java code is just wrong. It does not implicitly do any conversion, it just fails to compile.
There wasn't enough information in the OP's post for me to easily try out the Java code (what dependencies? what versions?) and the OP accepted my answer so... shrug
Sure, your answer is totally right, they just need a specific way to convert a String to a Foo. It's just that Java never does any implicit conversions except for upcasts, and ServerAddress is clearly not a supertype of String, so we can easily tell that the Java code also doesn't compile.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.