【问题标题】:Lambdas and generics in Java 8Java 8 中的 Lambda 和泛型
【发布时间】:2012-12-07 10:38:06
【问题描述】:

我正在使用未来的 java 8 版本,即 JDK 1.8。

我发现你可以轻松做到

interface Foo { int method(); }

并像使用它

Foo foo = () -> 3;
System.out.println("foo.method(); = " + foo.method());

只打印 3。

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

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 步骤?

【问题讨论】:

  • Mapper&lt;Integer, Integer&gt; times3 也许?
  • 现在我开始了解泛型,它们附带了 THIS :-(...
  • 其实在最新的build里,已经没有接口Mapper了。现在叫Function。有一些原始版本称为IntFunctionLongFunctionDoubleFunction
  • Function&lt;Integer, Integer&gt; times3 使用当前的 JDK8

标签: java lambda java-8


【解决方案1】:

@joop 和 @edwin 谢谢。

根据 JDK 8 的最新版本,应该这样做。

IntFunction<Integer> times3 = (Integer triple) -> 3 * triple;

如果你不喜欢,你可以用类似的东西让它更流畅

IntFunction times3 = triple -> 3 * (Integer) triple;

因此您不需要指定类型或括号,但您需要在访问参数时强制转换。

【讨论】:

  • 等等。演员在那里做什么? triple 会成为对象吗?您是否建议然后转换为Integer,而不是int
  • 我认为 (int) cast 不会编译。
  • IntFunction 和 Function 有什么区别?
  • IntFunction 将 int 作为参数。 Function 一个整数。它是经典的 java 原语与其包装类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-16
  • 1970-01-01
  • 1970-01-01
  • 2020-04-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多