4

I have java package There is Host class and Client class that can reveive many hosts

public final class Host {
   public final String name;
   public final int port; 
} 

public class SomeClient{...
   public Client(Host... hosts) throws Exception {
  ....
}

I'm writing scala code to creating this client

//  the hosts example is hosts1,host2,host3
def getClient(hosts:String) :SomeClient ={
   val default_port:Int = 100
   val hostsArr: Array[String] =hosts.split(",")
   new Client (hostArr ???)
 }

How can I map and convert scala array of strings to Host[], so the client will be created properly?

3 Answers 3

11
def getClient(hosts:String): SomeClient = {

    val default_port:Int = 100
    val hostsArr: Array[String] = hosts.split(",")

    //Here you map over array of string and create Host object for each item 
    val hosts = hostsArr map { hostStr =>
        val host = new Host()
        //Rest of assignment

        host
    }

    new Client(hosts:_*)
}

You can check the scala reference for repeated parameters section 4.6.2

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

Comments

0

So, actually your Scala array is already a Java array. You need to map your string array to Host array like:

val hosts = hostsArr.map { h => 
   val host = new Host()
   host.name = h
   host.port = default_port

   host
}

new Client(hosts)

2 Comments

That's doesn't compiles with (Host... hosts) signature :-( I need to convert it to Host[] somehow ...
Hm. I think, I forgot varargs: new Client(hosts : _*) ?
0

I have provided the basic Scala example of the Elasticsearch client here, where it accepts many hosts/nodes(Array/List of hosts) as a parameter. I have used Java Varargs(:_*) as mentioned by @Fatih Donmez.

Comments

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.