Search code examples
javafunctional-programming

How is a getter method of a class a Function<ThisObject, ReturnType> if a getter doesn't take in anything?


https://medium.com/quick-code/java-8-functional-programming-how-i-do-f11239a0aa90

I'm looking at this article because I was wondering how to implement getters in functional interfaces for long xml-type nested objects (basically trying to figure out if I can chain getters to get a deeply nested object that represents an XML tree).

The part that confuses me is how a getter is a Function<City, String>. Do non static methods always take in the object that the method corresponds to? I've read a lot of the docs but I don't see any of this mentioned. Can someone point me in the right direction here?

Why City::getName not supplier? Getters don't take in anything.


Solution

  • If you want to express City::getName, the lambda could also be written accordingly, maybe makes it more concise to understand what exactly happens:

    final Function<City, String> getPrice = c -> c.getName();
    

    Additional to the discussion, why is it a Function and not a Supplier: In contrast to the Supplier, the Function takes an argument. So the use-case would be different.

    1. With Supplier, you would always base on the same City, eg.
       final City city = currentCity
       supplier = () -> city.getName()
       // or
       supplier = city::getName
      
    2. With Function<City,String>, you would always provide the instance to the Function:
       func = (city) -> city.getName()
       // or
       func = City::getName