我正在玩 future 的 Java 8 版本,也就是 JDK 1.8。
我发现你可以轻松做到
interface Foo { int method(); }
像这样使用它
Foo foo = () -> 3;
System.out.println("foo.method(); = " + foo.method());
它只打印 3。
而且我还发现有一个 java.util.function.Function 接口(interface)以更通用的方式执行此操作。但是这段代码无法编译
Function times3 = (Integer triple) -> 3 * triple;
Integer twelve = times3.map(4);
看来我首先必须做类似的事情
interface IntIntFunction extends Function<Integer, Integer> {}
IntIntFunction times3 = (Integer triple) -> 3 * triple;
Integer twelve = times3.map(4);
所以我想知道是否有另一种方法可以避免 IntIntFunction 步骤?
最佳答案
感谢@joop 和@edwin。
基于 JDK 8 的最新版本,这应该可以做到。
IntFunction<Integer> times3 = (Integer triple) -> 3 * triple;
如果你不喜欢,你可以用类似的东西让它更平滑一些
IntFunction times3 = triple -> 3 * (Integer) triple;
因此您不需要指定类型或括号,但您需要在访问参数时强制转换它。
关于java - Java 8 中的 Lambda 和泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13761405/