开发者

Java: general function X->Y interface

开发者 https://www.devze.com 2023-01-19 07:32 出处:网络
I need an interface like: interface Fun开发者_StackOverflow中文版ction<X,Y> { Y eval(X obj);

I need an interface like:

interface Fun开发者_StackOverflow中文版ction<X,Y> {
    Y eval(X obj);
}

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


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);
 }


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.


There is a built-in interface like this, although it's only compatible with Java 8 onwards. You can find it here.

From the Javadocs:

public interface Function<T,R>

Represents a function that accepts one argument and produces a result.

This is a functional interface whose functional method is apply(Object).

Type Parameters:
T - the type of the input to the function
R - the type of the result of the function


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); 


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号