8

I'm using Guava collections' transform functions, and finding myself making a lot of anonymous functions like this pseudocode:

    Function<T, R> TransformFunction = new Function<T, R>() {
        public R apply(T obj) {
            // do what you need to get R out of T
            return R;
        }
    };

...but since I need to reuse some of them, I'd like to put the frequent ones into a class for easy access.

I'm embarrassed to say (since I don't use Java much), I can't figure out how to make a class method return a function like this. Can you?

ewall
  • 27,179
  • 15
  • 70
  • 84
  • 1
    I think it would help if you narrowed it down a little... give an example of a method you want to write that returns a `Function`, and how you'd use the method. At the moment, several responders have taken stabs at what they think you want, and it looks to me like they've all missed. – ajb Apr 11 '15 at 23:15

2 Answers2

11

I think what you want to do is make a public static function that you can re-use throughout your code.

For example:

  public static final Function<Integer, Integer> doubleFunction = new Function<Integer, Integer>() {
    @Override
    public Integer apply(Integer input) {
      return input * 2;
    }
  };

Or if you want to be cool and use lambdas

public static final Function<Integer, Integer> doubleFunction = input -> input * 2;
satnam
  • 10,719
  • 5
  • 32
  • 42
2

Simply encapsulate it into a class:

public class MyFunction implements Function<T, R> {
    public R apply(T obj) {
        // do what you need to get R out of T
        return R;
    }
};

Then you can use the class in client code like this:

Function<T, R> TransformFunction = new MyFunction();

If your functions are related to each other, you could also encapsulate them into an enum, because enums can implement interfaces.

Ingo Bürk
  • 19,263
  • 6
  • 66
  • 100
Mick Mnemonic
  • 7,808
  • 2
  • 26
  • 30