Tuesday, 13 December 2011

Compilation error due to method ambguity - Java

Today I encountered some new compilation error (atleast to me it's new). For example, there are two methods in the class.

public void doSomething(String value) {
// do something

public void doSomething(Long value) {
// do something with Long

And if you try to call this method


The compilation error will occur and states that, The method doSomething(String) is ambiguous for the type AmbguityTest. This is due to the fact that, the compiler doesn't know which method to invoke since both accepts a null value.

The solution is to add a cast to the argument. So, we can call like this.

doSomething((String)null); // To call String version
doSomething((Long)null); // To call Long version