4

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?

1 Answer 1

9

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]
Sign up to request clarification or add additional context in comments.

7 Comments

Isn't that only for Scala varargs?
It appears you're right. I don't think that always used to be the case. Is this new since 2.12?
@Jasper-M I ran this on 2.11.8
Yes, it seems to have always been like that. Now I wonder why I thought it wasn't...
@Jasper-M The oldest I found is a forum question from 2010 with Scala 2.8.0 claiming this works.
|

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.