2

我想知道是否有人以及在哪里完成了定义一组通用功能接口以简化和标准化 lambda 的使用的工作。我来自 C#,核心库完成了这项工作。

我读过“BiFunction”,发现它很笨拙。特别是当扩展到 TriFunction 等时。

我想出了以下内容:

public interface FI {
@FunctionalInterface
public interface Action<T> {
    void invoke(T arg1);
}
@FunctionalInterface
public interface Function0<TResult> {
    TResult invoke();
}
@FunctionalInterface
public interface Function1<Targ1, TResult> {
    TResult invoke(Targ1 arg1);
}
@FunctionalInterface
public interface Function2<Targ1, Targ2, TResult> {
    TResult invoke(Targ1 arg1, Targ2 arg2);
}
@FunctionalInterface
public interface Function3<Targ1, Targ2, Targ3, TResult> {
    TResult invoke(Targ1 arg1, Targ2 arg2, Targ3 arg3);
}
@FunctionalInterface
public interface Function4<Targ1, Targ2, Targ3, Targ4, TResult> {
    TResult invoke(Targ1 arg1, Targ2 arg2, Targ3 arg3, Targ4 arg4);
}
@FunctionalInterface
public interface Function5<Targ1, Targ2, Targ3, Targ4, Targ5, TResult> {
    TResult invoke(Targ1 arg1, Targ2 arg2, Targ3 arg3, Targ4 arg4, Targ5 arg5);
}
@FunctionalInterface
public interface Function6<Targ1, Targ2, Targ3, Targ4, Targ5, Targ6, TResult> {
    TResult invoke(Targ1 arg1, Targ2 arg2, Targ3 arg3, Targ4 arg4, Targ5 arg5, Targ6 arg6);
}
@FunctionalInterface
public interface Function7<Targ1, Targ2, Targ3, Targ4, Targ5, Targ6, Targ7, TResult> {
    TResult invoke(Targ1 arg1, Targ2 arg2, Targ3 arg3, Targ4 arg4, Targ5 arg5, Targ6 arg6, Targ7 arg7);
}
@FunctionalInterface
public interface Function8<Targ1, Targ2, Targ3, Targ4, Targ5, Targ6, Targ7, Targ8, TResult> {
    TResult invoke(Targ1 arg1, Targ2 arg2, Targ3 arg3, Targ4 arg4, Targ5 arg5, Targ6 arg6, Targ7 arg7, Targ8 atg8);
}
@FunctionalInterface
public interface Function9<Targ1, Targ2, Targ3, Targ4, Targ5, Targ6, Targ7, Targ8, Targ9, TResult> {
    TResult invoke(Targ1 arg1, Targ2 arg2, Targ3 arg3, Targ4 arg4, Targ5 arg5, Targ6 arg6, Targ7 arg7, Targ8 atg8, Targ9 arg9);
}
@FunctionalInterface
public interface Function10<Targ1, Targ2, Targ3, Targ4, Targ5, Targ6, Targ7, Targ8, Targ9, Targ10, TResult> {
    TResult invoke(Targ1 arg1, Targ2 arg2, Targ3 arg3, Targ4 arg4, Targ5 arg5, Targ6 arg6, Targ7 arg7, Targ8 atg8, Targ9 arg9, Targ10 arg10);
}

}
4

3 回答 3

2

javaslang[1] 提供Function0-Function8甚至CheckedFunction0- CheckedFunction8。它们甚至提供了额外的功能,比如“记忆”和“柯里化”。

http://javaslang.io

于 2016-08-17T10:34:03.167 回答
0

在 Java 8 中,官方只存在 4 种类型的函数。

  Consumer: Void function
  Function: receive argument return argument
  BiFunction: Receive 2 arguments return argument
  Predicate: receive argument return boolean

在这里你可以看到一些关于它的例子。

https://github.com/politrons/reactive/blob/master/src/test/java/stream/Functions.java

于 2016-07-20T08:11:31.590 回答
0

您会在java.util.function包装中找到最接近的类似物:

interface Function<T,R> { R apply(T t) }

interface Consumer<T> { void accept(T t) }

interface BiFunction<T,U,R> { R apply(T t, U u) }

等等。您可以定义自己的,或者您可以在例如Google Guava或其他库中找到一些。

于 2016-07-20T08:12:47.247 回答