3

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.

5
  • I'm not familiar with Scala, but it sounds like Scala uses it own class to marshall arguments in a variable-length function. This is different from Java, which passes them as an array. Commented Sep 8, 2014 at 20:30
  • 1
    It looks like the simplest way to get a Seq from java is to use [JavaConversions][1] [1]: stackoverflow.com/questions/6784593/… Commented Sep 8, 2014 at 20:31
  • 1
    @scala.annotation.varargs can usually help in situations like this, but not for constructors, and apparently not for ItemChain.apply, although you don't get an error if you put it in from of the case class definition (which is a little surprising to me). Put it on a create method in the companion object and you should be good to go, though. Commented Sep 8, 2014 at 20:39
  • @DPM You should post your comment as the answer. Commented Sep 8, 2014 at 20:58
  • I did, stackoverflow auto-converted it to a comment because it was short :) Looks like he got what he needed, which is what matters. Commented Sep 9, 2014 at 0:32

1 Answer 1

4

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());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.