12

Why do all scala vararg methods, when used from java, seem to accept a Seq of variables, and can't be used as java native vararg methods. Is this a bug?

For instance, Buffer has method def append(elems: A*): Unit. But in java it has another signature: void append(Seq<A>).

3 Answers 3

18

If you control the scala code you can use @varargs to make it generate a java-compatible varags method, e.g. @varargs def append(elems: A*): Unit = {}

Sign up to request clarification or add additional context in comments.

Comments

8

It is not a bug. It is a design choice that favors vararg use within Scala over interoperability with Java. For example, it allows you to pass a List into a Scala varargs method without having to convert it to an Array on the way.

If you need to use Scala varargs from Java, you should create some scala Seq instead. You can, for example, write a Java wrapper to get an array automatically created, and then use the genericWrapArray method from the Predef object.

1 Comment

-6

you can easily cast a Seq in varargs using :_*. For example :

val b = collection.mutable.ListBuffer.empty[Int]
b.append(List(1, 2):_*)

so this avoid code duplication in the collection API.

You can also simply use appendAll :

b.appendAll((List(1, 2))

4 Comments

Well, yes, I can, but how does that answer my question?))
I've just modified my answer.
The problem is not that Seq can't be casted to varargs in scala. The problem is that I have to create a Seq in Java to use a method with varargs.
Downvoted as you are still answwering a different question than the one asked.

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.