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
?
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.
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.
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().
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With