是否可以将引用运算符与其他运算符结合使用?
Is it possible to use the reference operator in conjunction with other operators?
假设我们得到了这个 class:
public class MyClass {
final int value = 0;
public int getValue() {
return value;
}
}
是否有可能以某种方式获取 getValue()
方法的输出并递增它,或者用它做任何数学运算,但是 使用参考运算符 而不是拉姆达?
我想要实现的是这样的,但是使用引用运算符:
Function<MyClass, Integer> getVal = x -> x.getValue() + 1;
如果我这样写,会报错:
Function<MyClass, Integer> getVal = MyClass::getValue + 1;
我不知道这是 lambda 表达式的问题,但您始终可以包装您的表达式并使用对这些包装器的引用
stream.map(this::doIt)
public int doIt(MyClass x){
return x.getValue()+1;
}
不行,那不行。
方法引用是一个表达式,它有一个值。值的类型在 compile-time 处计算,具体取决于使用它的上下文(这称为 多边形表达式 )。方法引用始终是 功能接口 .
的实例
在您的情况下,MyClass::getValue
returns 一些兼容的接口,但是表达式 MyClass::getValue + 1
导致 +
运算符必须处理该接口。
在 JLS § 15.13.3 中,您可以阅读有关方法引用的内容。
假设我们得到了这个 class:
public class MyClass {
final int value = 0;
public int getValue() {
return value;
}
}
是否有可能以某种方式获取 getValue()
方法的输出并递增它,或者用它做任何数学运算,但是 使用参考运算符 而不是拉姆达?
我想要实现的是这样的,但是使用引用运算符:
Function<MyClass, Integer> getVal = x -> x.getValue() + 1;
如果我这样写,会报错:
Function<MyClass, Integer> getVal = MyClass::getValue + 1;
我不知道这是 lambda 表达式的问题,但您始终可以包装您的表达式并使用对这些包装器的引用
stream.map(this::doIt)
public int doIt(MyClass x){
return x.getValue()+1;
}
不行,那不行。
方法引用是一个表达式,它有一个值。值的类型在 compile-time 处计算,具体取决于使用它的上下文(这称为 多边形表达式 )。方法引用始终是 功能接口 .
的实例在您的情况下,MyClass::getValue
returns 一些兼容的接口,但是表达式 MyClass::getValue + 1
导致 +
运算符必须处理该接口。
在 JLS § 15.13.3 中,您可以阅读有关方法引用的内容。