Java 8中的Lambdas和泛型

Nat*_*Cox 15 java lambda java-8

我正在玩未来的Java 8版本,即JDK 1.8.

我发现你很容易做到

interface Foo { int method(); }
Run Code Online (Sandbox Code Playgroud)

并使用它

Foo foo = () -> 3;
System.out.println("foo.method(); = " + foo.method());
Run Code Online (Sandbox Code Playgroud)

只打印3.

我还发现有一个java.util.function.Function接口以更通用的方式执行此操作.但是这段代码不会编译

Function times3 = (Integer triple) -> 3 * triple;
Integer twelve = times3.map(4);
Run Code Online (Sandbox Code Playgroud)

似乎我首先要做的事情

interface IntIntFunction extends Function<Integer, Integer> {}

IntIntFunction times3 = (Integer triple) -> 3 * triple;
Integer twelve = times3.map(4);
Run Code Online (Sandbox Code Playgroud)

所以我想知道是否有另一种方法可以避免IntIntFunction步骤?

Nat*_*Cox 5

@joop和@edwin谢谢.

根据JDK 8的最新版本,这应该做到这一点.

IntFunction<Integer> times3 = (Integer triple) -> 3 * triple;
Run Code Online (Sandbox Code Playgroud)

如果你不喜欢,你可以用类似的东西使它更平滑

IntFunction times3 = triple -> 3 * (Integer) triple;
Run Code Online (Sandbox Code Playgroud)

因此,您无需指定类型或括号,但在访问时需要转换参数.