views:

124

answers:

4

Hi,

I need an interface like:

interface Function<X,Y> {
    Y eval(X obj);
}

Is there something like this in Java already or do I need to define my own?

+10  A: 

Check out Guava, it has a Function interface:

public interface Function<F, T> {
  /**
   * Applies the function to an object of type {@code F}, resulting in an object of     type {@code T}.
   * Note that types {@code F} and {@code T} may or may not be the same.
   *
   * @param from the source object
   * @return the resulting object
   */
  T apply(@Nullable F from);

  /**
   * Indicates whether some other object is equal to this {@code Function}. This     method can return
   * {@code true} <i>only</i> if the specified object is also a {@code Function} and, for every
   * input object {@code o}, it returns exactly the same value. Thus, {@code
   * function1.equals(function2)} implies that either {@code function1.apply(o)} and {@code
   * function2.apply(o)} are both null, or {@code function1.apply(o).equals(function2.apply(o))}.
   *
   * <p>Note that it is always safe <i>not</i> to override {@link Object#equals}.
   */
  boolean equals(@Nullable Object obj);
 }
Nathan Hughes
+1  A: 

In fact, considering your purpose is yours, and not Sun/Oracle one, you should define your own interface (as it defines the contract you want implementors of your interface to fullfil).

However, if some framework already exists with such interface, and its purpose is the same than yours, you could use its definition, but with the biggest caution.

Riduidel
+3  A: 

Unfortunately, there's no such thing in the core Java libraries. As a consequence, many libraries define their own function-like interface. If you happen to use such a library already, you can re-use the function it uses.

Jorn
A: 

You can use a library such as Apache Commons Functor which has useful functions such as:

UnaryFunction

T evaluate(A obj);

BinaryFunction

T evaluate(L left, R right); 
dogbane