How do I disambiguate in Scala between methods with vararg and without

Viewed 8397

I'm trying to use the java jcommander library from Scala. The java JCommander class has multiple constructors:

 public JCommander(Object object)  
 public JCommander(Object object, ResourceBundle bundle, String... args)   
 public JCommander(Object object, String... args)   

I want to to call the first constructor that takes no varargs. I tried:

jCommander = new JCommander(cmdLineArgs)

I get the error:

error: ambiguous reference to overloaded definition,
both constructor JCommander in class JCommander of type (x$1: Any,x$2: <repeated...>[java.lang.String])com.beust.jcommander.JCommander
and  constructor JCommander in class JCommander of type (x$1: Any)com.beust.jcommander.JCommander
match argument types (com.lasic.CommandLineArgs) and expected result type com.beust.jcommander.JCommander
jCommander = new JCommander(cmdLineArgs)

I've also tried using a named parameter, but got the same result:

jCommander = new JCommander(`object` = cmdLineArgs)

How do I tell Scala I want to call the constructor that doesn't take varargs?

I'm using Scala 2.8.0.

5 Answers

The way to avoid this ambiguity is to force the compiler to pick the overload that takes more than one argument, using Scala's collection explosion syntax to pass in a singleton collection:

import java.util.stream.Stream
val stream = Stream.of(List(1):_*)

You can call the constructor with varags, but pass an empty list of varags.

(Of course, if you know that constructing JCommander with empty varags will produce the same result as calling the overloaded constructor (or method) without vargs)

jCommander = new JCommander(cmdLineArgs, Nil: _*)

Related