【发布时间】:2016-07-01 14:06:17
【问题描述】:
我有以下例子:
public class App {
public static void main( String[] args ) {
List<Car> list = Arrays.asList(new Car("green"), new Car("blue"), new Car("white"));
//Ex. 1
List<String> carColors1 = list.stream().map(CarUtils::getCarColor).collect(Collectors.toList());
//Ex. 2
List<String> carColors2 = list.stream().map(Car::getColor).collect(Collectors.toList());
}
static class CarUtils {
static String getCarColor(Car car) {
return car.getColor();
}
}
static class Car {
private String color;
public Car(String color) {
this.color = color;
}
public String getColor() {
return color;
}
}
}
例如。 1 有效,因为CarUtils 类中的方法getCarColor 具有与Function 接口中的apply 方法相同的方法签名和返回类型。
但是为什么前。 2作品? Car 类中的方法 getColor 与 apply 方法签名不同,我预计此处会出现编译时错误。
【问题讨论】:
-
您可以将方法
getColor视为具有传递给该方法的隐式this参数。有些语言明确表示这一点。所以你基本上有一个函数,它接受一个Car的实例并返回一个String。