smeeb
smeeb

Reputation: 29497

Scala Array[String] to Java String varargs

I have some Scala code that needs to call a Java 7 method that is defined as follows:

public void addListener(InputListener listener, String... mappingNames) {
    <details omitted here for brevity>
}

Here is my Scala code that call addListener:

inputManager.addListener(myListener, getActionInputs())

// Then the getActionInputs method:
def getActionInputs() : Array[String] = {
  Array("Red", "Fruit", "Cow")
}

This yields a compiler error:

Type mistmatch, expected: String, actual: Array[String]

I tried importing the Java/Scala conversions classes to convert my Scala Array[String] to a Java array, but have not been successful. Any ideas as to what the fix is?

Upvotes: 4

Views: 1834

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

You need to add :_* to transform the Array[String] to varargs:

Java:

public class C {
    public void addListener(String... mappingNames) {
        System.out.println(Arrays.toString(mappingNames));
    }
}

Scala:

def main(args: Array[String]): Unit = {
  val c = new C
  c.addListener(Array("a", "b", "c") :_*)
}

Yields:

[a, b, c]

Upvotes: 9

Related Questions