Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most specific method with matches of both fixed/variable arity (varargs)

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?

like image 654
oxbow_lakes Avatar asked Jan 23 '23 07:01

oxbow_lakes


1 Answers

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

like image 186
alexh Avatar answered Jan 25 '23 20:01

alexh