I have the following example:
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;
}
}
}
Ex. 1 works since method getCarColor
in CarUtils
class has the same method signature and return type as apply
method in Function
interface.
But why Ex. 2 works? Method getColor
in Car
class has a different from apply
method signature and I expect to get a compile time error here.