Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 462
smeeb Avatar asked Jan 05 '23 07:01

smeeb


1 Answers

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]
like image 196
Yuval Itzchakov Avatar answered Jan 10 '23 18:01

Yuval Itzchakov