How to use Scala varargs from Java code

前端 未结 1 1968
迷失自我
迷失自我 2020-12-10 11:27

There are plenty of articles on calling Java varargs from Scala code, but the only thing I could find the opposite way round was this question: Using scala vararg methods in

相关标签:
1条回答
  • 2020-12-10 12:03

    You can use:

    scala.collection.Seq$.MODULE$.empty();
    

    from Java code to create an empty sequence. Otherwise, you can use:

    new scala.collection.mutable.ArrayBuffer();
    

    to create an empty array buffer into which you can then add elements and use it as an argument to Scala vararg methods.

    Otherwise, if you design a Scala library with vararg methods which you want to use from Java code, then use the varargs annotation. It will generate a Java version of the method which takes an array instead of a Seq.

    scala> class A {
         |   @annotation.varargs def foo(x: Int*) { println(x) }
         | }
    defined class A
    
    scala> println(classOf[A].getMethods.toList)
    List(public void $line1.$read$$iw$$iw$A.foo(scala.collection.Seq), public void $line1.$read$$iw$$iw$A.foo(int[]), ...)
    

    Above, reflection shows that there are 2 versions of method foo generated - one that takes a Seq[Int] and another which takes an int[].

    0 讨论(0)
提交回复
热议问题