Search code examples
javascalacross-languagevariadic-functions

Syntax for Calling a variable-length parameter Scala function from Java?


I have a Scala class whose constructor takes a variable-length parameter list.

case class ItemChain(items: Item*)

From Scala it can be called like so

ItemChain(Item(), Item())

I can't figure out the syntax for calling it from Java. If I do this

new ItemChain(new Item(), new Item())

I get a compiler error that says this line does not match the signature scala.collection.seq<Item>.

I can directly instantiate the Scala sequence object from Java.

new scala.collection.Seq<Item>()

But I can't figure out how to subsequently add my two Item instances to it. If I create a Java List of Items and cast it toscala.collection.Seq I get a runtime error.


Solution

  • This should do the trick:

    import static scala.collection.JavaConverters.asScalaBufferConverter;
    import static java.util.Arrays.asList;
    
    ...
    
    new ItemChain(asScalaBufferConverter(asList(new Item(), new Item())).asScala());