简体   繁体   中英

Java - Why am I forced to cast a reference constructor into a Supplier, otherwise Java claims the method is ambigous?

I have the following defined interface which is intended to be implemented by all the implementations of a 3d vector:

public interface IVector3<T extends Number> extends IVector<T> {
    // Other stuff

    public static <T extends Number, V extends IVector3<T>> V cross(V target, IVector3<?> vector0, IVector3<?> vector1) {
        // Implementation
    }

    public static <T extends Number, V extends IVector3<T>> V cross(Supplier<V> factory, IVector3<?> vector0, IVector3<?> vector1) {
        return cross(factory.get(), vector0, vector1);
    }
}

I've also defined the follow implementation of the interface:

public class Vector3f extends Vectorf implements IVector3<Float> {
    // Other stuff

    public static Vector3f cross(IVector3<?> vector0, IVector3<?> vector1) {

        // The annoying required cast
        return IVector3.cross((Supplier<Vector3f>) Vector3f::new, vector0, vector1);
    }
}

So, why does java requires me to make that cast of the reference constructor otherwise it claims the call to the method to be ambiguous?

Shouldn't the bounded type parameter solve the ambiguity?

And finally, is there any solution to avoid having to cast the reference constructor without changing the bounded type parameters?

Note : No other class/interface in the hierarchy defines a method (static or not) named "cross".

Note 2 : I'm using Java 12.

Primarily since it's unable to infer the type via the method reference or even lambda. If only you would let it know the type context with which you are invoking the cross method, it shall work. For example this -

return IVector3.<Float, Vector3f>cross(Vector3f::new, vector0, vector1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM