Java 8: Reference to [method] is ambiguous [duplicate]

Your problem is a side-effect of Generalized Target-type Inference, an improvement in Java 8.

What is Target-type Inference

Let’s take your example method,

public static <R> R get(String d) {
    return (R)d;
}

Now, in the method above, the generic parameter R cannot be resolved by the compiler because there’s no parameter with R.

So, they introduced a concept called Target-type Inference, which allows the parameter to be inferred based on the assignment parameter.

So, if you do,

 String str = get("something"); // R is inferred as String here
 Number num = get("something"); // R is inferred as Number here

This works well in Java 7. But the following does not,

put(get("something");
static void Put(String str) {} //put method

Because type inference worked only for direct assignments.

If there’s no direct assignment, then the generic type was inferred as Object.

So, when you compiled the code with Java 7, your put(Object) method was called without any problems.

What they did in Java 8

They improved the type inference to infer the type from method calls and chained method calls

More details about them here and here

So now, you can directly call put(get("something")) and the generic type will be inferred based on the parameter of the put() method.

But as you know, the methods, put(Charsequence) and put(char[]) match the arguments. So there’s the ambiguity.

Fix?

Just tell the compiler exactly what you want,

put(TestClass.<CharSequence>get("hello")); // This will call the put(CharSequence) method.

Leave a Comment

deneme bonusu veren sitelerbahis casino