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?
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.
Rules for varargs:There can be only one variable argument in the method. Variable argument (varargs) must be the last argument.
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[].
Varargs is a short name for variable arguments. In Java, an argument of a method can accept arbitrary number of values.
// 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With