如何将scala数组转换为Java数组[]

时间:2015-10-21 04:35:53

标签: scala

我有java包 有Host类和Client类可以显示许多主机

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

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

我正在编写scala代码来创建此客户端

//  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 ???)
 }

如何将scala数组字符串映射并转换为Host [],以便正确创建客户端?

3 个答案:

答案 0 :(得分:6)

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:_*)
}

您可以查看repeated parameters部分4.6.2

的scala参考

答案 1 :(得分:0)

所以,实际上你的Scala数组已经是一个Java数组了。您需要将字符串数组映射到Host数组,如:

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

   host
}

new Client(hosts)

答案 2 :(得分:0)

我提供了Elasticsearch客户端here的基本Scala示例,其中它接受许多主机/节点(数组/主机列表)作为参数。我使用了{Fatih Donmez提到的Java Varargs(:_*)