我正在学习 Java-8 Lambda,我试图了解 java.util.function.Function 接口(interface)中的 addThen 默认方法。根据我的理解,addthen 将首先执行第一个函数,然后执行第二个方法。 所以我创建了一个如下所示的程序:
//Pojo class
class Bike {
public Bike(String bikeName, int price, String bikeType) {
this.bikeName = bikeName;
this.price = price;
this.bikeType = bikeType;
}
private String bikeType;
private String bikeName;
private int price;
public String getBikeType() {
return bikeType;
}
@Override
public String toString() {
return "Bike [bikeType=" + bikeType + ", bikeName=" + bikeName + ", price=" + price + "]";
}
public void setBikeType(String bikeType) {
this.bikeType = bikeType;
}
public String getBikeName() {
return bikeName;
}
public void setBikeName(String bikeName) {
this.bikeName = bikeName;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
//Main class
public class FunctionInbuildDefaultMethodsExample {
public static void main(String[] args) {
learningAndThen();
}
static void learningAndThen() {
Function<Bike, String> updateBikefunction = (Bike bike) -> {
System.out.println("OldBike Name is::" + bike.getBikeName());
bike.setBikeName("PULSOR-200CC");
return bike.getBikeName();
};
Function<Bike, String> updateBikePriceFunction = (Bike bike) -> {
System.out.println("OldBike Price is::" + bike.getPrice());
bike.setPrice(95000);
return bike.getBikeName();
};
/*
* First update Bike and then price
* */
/*Compilation error here*/
Function<Bike,String> bikeFunction = updateBikefunction.andThen(updateBikePriceFunction);
bikeFunction.apply( new Bike("PULSOR-125CC", 65000, "BAJAJ"));
}
}
我在该行遇到编译错误
Function<Bike,String> bikeFunction =
updateBikefunction.andThen(updateBikePriceFunction);
作为
"The method andThen(Function) in the type Function is not applicable for the arguments (Function)"
, 看了 Function 接口(interface)的源码,明白了
addThen 默认方法正在寻找 Function<String,Book>
类型的实例.我的问题是,如果addThen
默认方法应该执行第一个函数,然后执行作为参数传递的下一个函数,为什么 addThen
函数接口(interface)的默认方法是这样写的,除了Function<String,Book>
类型的实例.
最佳答案
andThen
应用于该 Function
的结果。所以这会起作用,例如:
Function<Bike, String> bikeFunction = updateBikefunction
.andThen(s -> s.toUpperCase());
因为结果是 Function
的 String
。
关于Java 8 Function类addThen默认方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45840136/