gpt4 book ai didi

java - Lambda 和泛型 : Why Does This Compile?

转载 作者:行者123 更新时间:2023-12-01 22:23:03 24 4
gpt4 key购买 nike

这是我的代码的一个简短示例来证明我的观点:

public class Tmp {

static class X {
void setStr(String blah) {
}
String getStr() {
return null;
}
}

public void test() {
createCheck(X::getStr, ""); // supposed to compile
createCheck(X::getStr, 123); // rather not: int isn't String
}

private <T, V> BiPredicate<T, String> createCheck(Function<T, V> func, V value) {
return new BiPredicate<T, String>() {

@Override
public boolean test(T t, String ref) {
assertThat(func.apply(t))
.as(ref)
.isEqualTo(value);
return true;
}

};
}

}

恕我直言,编译器应该看到 createCheck() 中的 V 应该是来自 getter 函数的 String,这就是为什么它应该提示int。或者反过来。

那么为什么会编译呢?

最佳答案

您的签名是:

private <T, V> BiPredicate<T, String> createCheck(Function<T, V> func, V value) {

您对 T 没有限制或 V所以绝对是 T 的任何值或 V会编译。

返回一个BiPredicate<T, String>然而,所以 isEqualTo方法采用 String ref并将其与 Object value 的相等性进行比较- 我认为这也是完全合法的isEqualTo需要 Object模仿 Object.equals 的行为.


在你的例子中:

createCheck(X::getStr, 123);

V就是Object因为这是可以应用于 String 的最严格的类型限制和 Integer .


您的意思是:

private <T> BiPredicate<T, String> createCheck(Function<T, String> func, String value) {

关于java - Lambda 和泛型 : Why Does This Compile?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38822972/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com