4

In section 15.12.2.5 of the Java Language Specification, it talks about how to choose the most specific method in both cases of methods with fixed arity and methods of variable arity (i.e. varargs).

What I can't find in the JLS is anything about deciding between two methods where one is of fixed arity and one of variable arity however. For example:

public interface SomeApi {
    public String getSomething(String arg);       // method 1
    public String getSomething(String ... args);  // method 2
}

Compiles just fine as one would expect (for reasons outlined by Yoni below). This calling code compiles also:

SomeApi api = ...
Object o = api.getSomething("Hello");

and if you run it, method #1 (i.e. the non-varargs method) is called. Why is this calling-code not ambiguous? Why is the fixed arity method more specific than the variable-arity one? Can someone point me to the relevant bit of the spec?

1
  • 1
    just curious... did you have a specific reason for understanding besides an academic interest? (I'm trying to implement runtime dispatch selection + wondered who else might be doing the same)
    – Jason S
    Commented May 16, 2011 at 21:08

2 Answers 2

10

The first method resolution phase considers only fixed arity methods and the process is terminated if a match is found, before any varargs methods are considered.

From http://docs.oracle.com/javase/specs/jls/se6/html/expressions.html#15.12.2.2

15.12.2.2 Phase 1: Identify Matching Arity Methods Applicable by Subtyping

If no method applicable by subtyping is found, the search for applicable methods continues with phase 2 (§15.12.2.3). Otherwise, the most specific method (§15.12.2.5) is chosen among the methods that are applicable by subtyping.

(My emphasis.)

1
  • Thanks Alex - I was not seeing the wood for the trees. Damn those trees! Commented Aug 24, 2009 at 11:42
-1

I can't point you to the spec, but logically,

getSomething(String...args) 

translates to

getSomething(String[] args)

with no ambiguity

1
  • Yes - I understand that. I was asking why the calling code is not ambiguous - I've clarified my intent in the question Commented Aug 24, 2009 at 10:55

Not the answer you're looking for? Browse other questions tagged or ask your own question.