14

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?

OutNSpace
  • 373
  • 2
  • 8

3 Answers3

3
// 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

chuchulo
  • 61
  • 6
0

I can't reproduce this on Scala 2.10.4 and Java 8 but it seems like a bug.

You can avoid the : _* by adding these Java methods:

public static MyJavaClass javaFuncConverter(String name, long[] values) {
     return javaFunc(name, values);
}

public static MyJavaClass javaFuncConverter(String name, long value) {
     return javaFunc(name, value);
}

In your Scala code you call it like this:

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

MyJavaClass.javaFuncConverter("hello", idList.toArray)
MyJavaClass.javaFuncConverter("hello", idList.head)
Boaz
  • 1,212
  • 11
  • 25
-1

This did the trick:

import scala.collection.JavaConverters._
val javaList = idList.asJava
OutNSpace
  • 373
  • 2
  • 8