为什么这种类型推断在这个Lambda表达式场景中不起作用?

20 浏览
0 Comments

为什么这种类型推断在这个Lambda表达式场景中不起作用?

在使用lambda表达式时,我遇到了一种奇怪的情况,类型推断并不按照我的预期工作。以下是我真实情况的一个近似示例:

static class Value {
}
@FunctionalInterface
interface Bar {
  T apply(Value value); // 在此处进行更改解决了错误
}
static class Foo {
  public static  T foo(Bar callback) {
  }
}
void test() {
  Foo.foo(value -> true).booleanValue(); // 在此处编译错误
}

我在倒数第二行得到的编译错误是:

The method booleanValue() is undefined for the type Object

如果我将lambda表达式转换为`Bar`:

Foo.foo((Bar)value -> true).booleanValue();

或者如果我更改`Bar.apply`方法的方法签名以使用原始类型:

T apply(Value value);

那么问题就消失了。我期望的工作方式是:

- `Foo.foo`调用应该推断出返回类型为`boolean`

- lambda表达式中的`value`应该被推断为`Value`

为什么这种推断不按照预期工作,我该如何更改此API以使其按预期工作?

0