Sunday, August 29, 2010

Eclipse Helios+ does not allow to overload methods changing just the return type

So far, many of us have found we can not overload methods which, when type erasure is applied, have the same signature. For example, the following:

import java.util.List;

public class MethodDuplicateDemo {

public int useAList(List<Integer> list) {
return list.size();
}

public int useAList(List<String> list) {
return list.size();
}
}


will not compile, giving these errors:

Method useAList(List<Integer>) has the same erasure useAList(List<e>) as another method in type MethodDuplicateDemo

Method useAList(List<String>) has the same erasure useAList(List<e>) as another method in type MethodDuplicateDemo


However, many were also used to being able to write:

import java.util.List;

public class MethodDuplicateDemo {

public int useAList(List<Integer> list) {
return list.size();
}

public String useAList(List<String> list) {
return list.toString();
}
}


(notice that one of the methods returns an int, while the other returns a String)

Well, the latter example will compile using javac (1.6), and will work on Eclipse up to version 3.5 (Galileo), but it does not compile on Eclipse Helios (3.6).

The reason: starting with Helios, Eclipse implements a java 7 restriction by which the return type should not be considered when deciding if the methods are duplicates. Even though this works with the java 6 compiler from the Sun JDK, it was implemented for all compliance levels in Eclipse. This is documented in https://bugs.eclipse.org/bugs/show_bug.cgi?id=289247 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=273862 .

So, time to start changing the code where it relies on the return types being different for compilation ;-)

No comments: