2

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.

user1745356
  • 4,462
  • 7
  • 42
  • 70
  • 3
    You can think of the method `getColor` as having an implicit `this` parameter that gets passed into the method. Some languages make this explicit. So you basically have a function that takes an instance of `Car` and returns a `String`. – Luka Jacobowitz Jul 01 '16 at 14:12

1 Answers1

3

Method getColor in Car class has a different from apply method signature and I expect to get a compile time error here.

Not really. Car.getColor() is an instance method. You can see it as a function that takes one argument: this, of type Car, and returns a String. So that matches with the signature of apply() in Function<Car, String>.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Let's say I have an instance method that takes two arguments. Does it actually have three arguments and the first would be an instance that the method belongs in? – user1745356 Jul 01 '16 at 14:21
  • 3
    If there are multiple parameters, the first parameter will always be the class instance. – Hank D Jul 01 '16 at 14:24