theomega
theomega

Reputation: 32051

Use `@annotation.varargs` on constructors

I want to declare a class like this:

class StringSetCreate(val s: String*) {
 // ...
}

and call that in Java. The problem is that the constructor is of type

public StringSetCreate(scala.collection.Seq)

So in java, you need to fiddle around with the scala sequences which is ugly.

I know that there is the @annotation.varargs annotation which, if used on a method, generates a second method which takes the java varargs.

This annotation does not work on constructors, at least I don't know where to put it. I found a Scala Issue SI-8383 which reports this problem. As far as I understand there is no solution currently. Is this right? Are there any workarounds? Can I somehow define that second constructor by hand?

Upvotes: 0

Views: 205

Answers (1)

lmm
lmm

Reputation: 17431

The bug is already filed as https://issues.scala-lang.org/browse/SI-8383 .

For a workaround I'd recommend using a factory method (perhaps on the companion object), where @varargs should work:

object StringSetCreate {
  @varargs def build(s: String*) = new StringSetCreate(s: _*)
}

Then in Java you call StringSetCreate.build("a", "b") rather than using new.

Upvotes: 1

Related Questions