Last active
August 26, 2019 18:38
-
-
Save hezamu/7300031 to your computer and use it in GitHub Desktop.
How to call a Java method with varargs from Scala.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
I ran into the "ambiguous reference to overloaded definition" error while trying to create a Vaadin ShortcutAction from Scala like this: | |
val upAction = new ShortcutAction("up", ShortcutAction.KeyCode.ARROW_UP, null) | |
ShortcutAction has a few constructors with repeating parameters (varargs), but specifying null as the last parameter clears things up in Java. Scala on the other hand seems unable to figure out which constructor I'm trying to call. | |
Now, Scala has a special syntax to tell the compiler to pass a Seq as varargs, ": _*". So, I figured out this would work: | |
val upAction = new ShortcutAction("up", ShortcutAction.KeyCode.ARROW_UP, Array(): _*) | |
But I get the same error as before. So, what about trying to pass null as varargs? | |
val upAction = new ShortcutAction("up", ShortcutAction.KeyCode.ARROW_UP, null: _*) | |
This actually crashes the Scala compiler (2.10.2) by failing an assertion. In the end I just created a simple wrapper class in Java: | |
public class MyShortcutAction extends ShortcutAction { | |
public MyShortcutAction(String caption, int keyCode) { | |
super(caption, keyCode, null); | |
} | |
public MyShortcutAction(String caption, int keyCode, int modifier) { | |
super(caption, keyCode, new int[] { modifier }); | |
} | |
} | |
This works from Scala with no problems. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Funciona correctamente en scala 2.11.1 también.
Muchas Gracias!