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?
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With