函数和谓词参数模糊不清? [英] Function and Predicate parameter ambiguous?

查看:140
本文介绍了函数和谓词参数模糊不清?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Java 8,我收到以下代码的编译错误:

Using Java 8, I get a compiler error for the following code:

public class Ambiguous {
    public static void call() {
        SomeDataClass data = new SomeDataClass();
        callee(data, SomeDataClass::getString);
        // compiler errors:
        // 1. at callee method name:
        // The method callee(SomeDataClass, Function<SomeDataClass,String>) is ambiguous for the type Ambiguous
        // 2. at lambda:
        // Type mismatch: cannot convert from boolean to String
        callee(data, d -> d.getRandom() > 0.5);
    }

    public static void callee(SomeDataClass data, Function<SomeDataClass, String> extractString) {
        System.out.println(extractString.apply(data));
    }

    public static void callee(SomeDataClass data, Predicate<SomeDataClass> check) {
        System.out.println(check.test(data));
    }
}

// token data class
final class SomeDataClass {
    public String getString() {
        return "string";
    }

    public final double getRandom() {
        return Math.random();
    }
}

基本上编译器说我知道你回来了 boolean 但是你不应该,如果你不这样做,我不知道使用什么方法而不是哦你要返回 boolean ,你必须指的是谓词版本的方法?这种混乱是如何产生的?

So essentially the compiler says "I know you return boolean but you shouldn't, and if you don't I'm not sure what method to use" instead of "oh you're returning boolean, you must mean the Predicate version of the method"? How does this confusion get created?

我知道如果 Predicate< T>扩展函数< T,布尔> (所以它们有一个共同的类型)但事实并非如此。

I'd understand if Predicate<T> extends Function<T, Boolean> (so they have a common Type) but that's not the case.

我知道如何修复它;如果我这样做就好了

I do know how to fix it; it's fine if I do

callee(data, (Predicate<SomeDataClass>) d -> d.getRandom() > 0.5);

但我很好奇是什么导致它。

but I'm curious what causes it.

推荐答案

为了清晰起见,这可以简化一下:

This can be simplified a bit for clarity:

public static void m(Predicate<Integer> predicate){

}

public static void m(Function<Integer, String> function){

}

并用以下方式调用:

m(i -> "test")

您认为会是什么?发生?与你的问题相同。

What do you think will happen? Same thing as in your question.

这里的编译器必须知道方法才能找到目标类型,但它需要知道目标类型才能解决方法(就像死锁一样)。

Compiler here has to know the method in order to find the target type, but it needs to know the target type in order to resolve the method (it's like a deadlock).

当你向谓词... 添加一个强制转换时,你正在创建显式目标类型,根据我的理解,返回类型被考虑用于方法重载。

When you add a cast to Predicate..., you are creating an explicit target type, return type of which is taken into consideration for method overloading as far as I understand.

这篇关于函数和谓词参数模糊不清?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆