Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass Scala Seq to a Java varargs

I have an existing Java method like this:

public static MyJavaClass javaFunc(String name, long... values) {
    ...
}

and I need to call it from Scala with this:

val idList: Seq[Long] = Seq(1L, 2L, 3L)

MyJavaClass.javaFunc("hello", idList)

but it ends up invoking the toString method on the idList parameter. I've tried the following to no avail:

MyJavaClass.javaFunc("hello", idList:_*)

which causes compile error:

no `: _*' annotation allowed here (such annotations are only allowed in arguments to *-parameters)

How can I pass the argument?

like image 342
OutNSpace Avatar asked Jun 14 '13 19:06

OutNSpace


People also ask

Is it good to use varargs in java?

Varargs are useful for any method that needs to deal with an indeterminate number of objects. One good example is String. format . The format string can accept any number of parameters, so you need a mechanism to pass in any number of objects.

What is the rule for using Varargs?

Rules for varargs:There can be only one variable argument in the method. Variable argument (varargs) must be the last argument.

How does Varargs work in Java?

Syntax of Varargs Hence, in the Varargs method, we can differentiate arguments by using Index. A variable-length argument is specified by three periods or dots(…). This syntax tells the compiler that fun( ) can be called with zero or more arguments. As a result, here, a is implicitly declared as an array of type int[].

What does Varargs mean?

Varargs is a short name for variable arguments. In Java, an argument of a method can accept arbitrary number of values.


1 Answers

// java class
public class MyJavaClass {
    public static void javaFunc(String name, long ...values) {
        for (long i: values)
            System.out.print(i + " ");
        System.out.println();
    }
}
//scala class
object Y {
  def main(args: Array[String]): Unit = {
    val idList: Seq[Long] = Seq(1L, 2L, 3L)
    MyJavaClass.javaFunc("hello", idList: _*)
  }
}

it is working like this for me

like image 120
chuchulo Avatar answered Sep 28 '22 07:09

chuchulo