19
public static void main(String... args){
    then(bar()); // Compilation Error
}

public static <E extends Exception> E bar() {
    return null;
}

public static void then(Throwable actual) { }

public static void then(CharSequence actual) { }

Compilation result (from command line javac Ambiguous.java)

Ambiguous.java:4: error: reference to then is ambiguous
        then(bar());
        ^
  both method then(Throwable) in Ambiguous and method then(CharSequence) in Ambiguous match
1 error

Why this method is ambiguous? This code compile with success under Java 7!

After changing method bar to:

public static <E extends Float> E bar() {
    return null;
}

This compiles without any problems, but is reported as error in IntelliJ Idea (Cannot resolve method then(java.lang.FLoat)).

This code fails under Java 7 - javac -source 1.7 Ambiguous.java:

Ambiguous.java:4: error: no suitable method found for then(Float)
        then(bar());
        ^
    method Ambiguous.then(Throwable) is not applicable
      (argument mismatch; Float cannot be converted to Throwable)
    method Ambiguous.then(CharSequence) is not applicable
      (argument mismatch; Float cannot be converted to CharSequence)
1 error

Java version

java version "1.8.0_40"
Java(TM) SE Runtime Environment (build 1.8.0_40-b25)
Java HotSpot(TM) 64-Bit Server VM (build 25.40-b25, mixed mode)
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
MariuszS
  • 30,646
  • 12
  • 114
  • 155
  • Will it help if I say that i've just successfully run your code with jdk1.8.0_40? Just pasted it to a fresh Idea project and clicked 'run' with junit annotation imported. The first one obviously -version with Float is definitely wrong on any java version, as per error you see. – marvin82 Apr 07 '15 at 19:56
  • 2
    @marvin82: in [*try Java8*](http://www.tryjava8.com/app/snippets/552436d9e4b017c2ee13ca34) it fails. – Willem Van Onsem Apr 07 '15 at 19:57
  • marvin82, it **compiles** fine with Float under java8, there is no error https://gist.github.com/mariuszs/0a82ca08f55499906ea9 – MariuszS Apr 07 '15 at 20:00
  • 2
    My bad, i had language level overriden. Sorry for confusion. – marvin82 Apr 07 '15 at 20:03

1 Answers1

21

Consider the following class:

public class Foo extends Exception implements CharSequence {
    //...
}

The class Foo implements both Throwable and CharSequence. So in case E is set to this instance, the Java compiler does not know which method to call.

The reason there is probably no problem for Java7 is that generics are less implemented. In case you don't provide an E yourself (e.g. (Foo) bar()), Java will fall back on the basic verion of E which is implements Exception, E is thus only considered to be an instance of Exception.

In Java8, the type inference is improved, the type of E is now derived from the parameter called for by then(), in other words the compiler first looks what possible types then() needs, the problem is that they both are valid choices. So in that case it becomes ambiguous.


Proof of concept:

Now we will slightly modify your code and show how ambiguous calls are resolved:

Say we modify the code to:

public class Main {
    public static void main(String... args){
        then(bar()); // Compilation Error
    }
    public static <E extends Exception> E bar() {
        return null;
    }
    public static void then(CharSequence actual) {
        System.out.println("char");
    }
}

If you run this in Java8, there is no problem (it prints char), because Java8 simply assumes there is such class Foo (it created some kind of "inner" type for it that derived from both).

Running this in Java7 yields problems:

/MyClass.java:18: error: method then in class MyClass cannot be applied to given types;
    then(bar()); // Compilation Error
    ^
  required: CharSequence
  found: Exception
  reason: actual argument Exception cannot be converted to CharSequence by method invocation conversion
1 error

It did a fallback on Exception and couldn't find a type that could deal with it.

If you run the original code in Java8, it will error because of the ambiguous call, if you run it in Java7 however, it will use the Throwable method.


In short: the compiler aims to "guess" what E is in Java8, whereas in Java7 the most conservative type was picked.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • 1
    so, in this case we should avoid mixing interfaces with classes? – MariuszS Apr 07 '15 at 19:58
  • 2
    @MariuszS: well you can make explicit (for instance with `(Exception) bar()` about which `E` you are talking. But in general maxing (non `final`) `class`es with `interface`s and `interface`s with `interface`s is looking for trouble I guess. – Willem Van Onsem Apr 07 '15 at 20:02
  • 4
    @MariuszS: No, generally, you should avoid to declare methods like `E bar()` which basically say “the caller can decide what `bar()`” returns. Since the only valid return value that can hold this promise is `null`, such methods make no sense. – Holger Apr 08 '15 at 09:00
  • @Holger: well in C# you can also add a `new()` constraint. In that case you force there should be a default constraint available. In that case, it becomes useful. As far as I know, that's not available in Java8, but eventually it can be implemented. – Willem Van Onsem Apr 08 '15 at 14:03
  • 2
    @CommuSoft: but when the method is ambiguous, how does C# know which type to instantiate? In Java 8 you can do such thing by adding a `Supplier` parameter to `bar()`, then the caller can use `then(bar(DesiredType::new))` to disambiguate by providing the appropriate `Supplier` at the same time… – Holger Apr 08 '15 at 14:17
  • @Holger: because in C# you are forced to provide the type explicitly, unless it is a `this` type (*extension methods*). I'm only saying that in the (near) future such `E` could become interesting (for reasons we do not yet know). Don't get me wrong, did +1 on your comment, currently it's not a good idea, but one must be careful with such statements I think. – Willem Van Onsem Apr 08 '15 at 14:20
  • @WillemVanOnsem can you explain why in Java 8 it worked for ` E bar()` scenario? Float being a final class, it never can be subclassed. Therefore in that case how a class Like `Foo` (extends Float and implements CharSequence ) exists? – Priyal Oct 13 '17 at 05:51