views:

169

answers:

2

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?

A: 

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

getSomething(String...args)

translates to

getSomething(String[] args)

with no ambiguity

Yoni Roit
Yes - I understand that. I was asking why the calling code is not ambiguous - I've clarified my intent in the question
oxbow_lakes
+6  A: 

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://java.sun.com/docs/books/jls/third_edition/html/expressions.html

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.)

alexh
Thanks Alex - I was not seeing the wood for the trees. Damn those trees!
oxbow_lakes
Those varargs are cursed!
pjp