Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 769
W.P. McNeill Avatar asked Aug 27 '26 06:08

W.P. McNeill


1 Answers

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());
like image 135
Eugene Loy Avatar answered Aug 29 '26 21:08

Eugene Loy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!