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.

W.P. McNeill
  • 16,336
  • 12
  • 75
  • 111
  • 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. – Powerlord Sep 08 '14 at 20:30
  • 1
    It looks like the simplest way to get a Seq from java is to use [JavaConversions][1] [1]: http://stackoverflow.com/questions/6784593/how-to-create-a-scala-collection-immutable-seq-from-a-java-list-in-java – DPM Sep 08 '14 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. – Travis Brown Sep 08 '14 at 20:39
  • @DPM You should post your comment as the answer. – W.P. McNeill Sep 08 '14 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. – DPM Sep 09 '14 at 00:32

1 Answers1

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());
Eugene Loy
  • 12,224
  • 8
  • 53
  • 79