Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

State in a java.util.function.Function

Suppose that I have a class which implements java.util.function.Function. The Function needs to know about a start date and end date but these will be constant throughout the lifetime of the function.

I'm considering implementing the Function with private final fields for the start and end dates, as the apply method doesn't require new values for them for each call. I feel that this will simplify my implementation but worry that this goes against the whole functional programming paradigm.

Is it reasonable to have immutable class members in a Function when the values are required by the apply method but are constant throughout the lifetime of the Function?

like image 374
Robert Bain Avatar asked Jun 17 '15 11:06

Robert Bain


People also ask

What is Java Util function function?

util. function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in one argument and produces a result.

What is function identity () in Java?

identity. static <T> Function<T,T> identity() Returns a function that always returns its input argument. Type Parameters: T - the type of the input and output objects to the function Returns: a function that always returns its input argument.

What functional interfaces would you use for the function descriptor T U )-> r?

BiFunction<T,U,R> functional interface, here T,U are generic input type and R is a type of output of operation and represents an operation that accepts one argument and returns a result of type R. It has a functional method as apply().


1 Answers

There is nothing wrong with your approach.

I feel that this will simplify my implementation but worry that this goes against the whole functional programming paradigm.

To solve this, you could implement a method, which gets your start and end date, and returns you a function. For example:

public static final Function<Object, Object> getDateF(final Date start, final Date end) {
  return input -> {
    // do something with start / end for your calculation
    final Object output = null;
    return output;
  };
}

Replace Object to whatever you need.

like image 175
Martin Seeler Avatar answered Oct 01 '22 18:10

Martin Seeler