Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java method that returns a function?

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?

like image 847
ewall Avatar asked Apr 11 '15 23:04

ewall


People also ask

How do you return a function in Java?

Returning a Value from a Method In Java, every method is declared with a return type such as int, float, double, string, etc. These return types required a return statement at the end of the method. A return keyword is used for returning the resulted value. The void return type doesn't require any return statement.

What is function return type in Java?

A return statement causes the program control to transfer back to the caller of a method. Every method in Java is declared with a return type and it is mandatory for all java methods. A return type may be a primitive type like int, float, double, a reference type or void type(returns nothing).

How do you call a method returning a value in Java?

To use the return value when calling a method, it must be stored in a variable or used as part of an expression. The variable data type must match the return type of the method.

Can a function return another function in Java?

You can't technically return a function, but you can return the instances of classes representing functions, in your case UnaryFunction .


1 Answers

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;
like image 64
satnam Avatar answered Sep 24 '22 00:09

satnam