将scala.Function1写为lambda的正确方法是什么?

时间:2016-09-29 14:38:12

标签: java scala lambda java-8

我正在尝试使用Java中的transform() Dataset,如下所示:

Function1<Dataset<Long>,Dataset<Long>> withDoubled = (Dataset<Long> numbers) -> numbers.withColumn("doubled",numbers.col("id").multiply(2));
spark.range(10).transform(withDoubled).show();  

然而,Function1<>被标记为错误,表示有多个抽象函数要覆盖。我怎么把它写成一个lambda?

1 个答案:

答案 0 :(得分:1)

与Scala的Function1一起使用lambda并不是直接的,因为lambda与Interface只有一个abstract联合-implemented函数,在Scala的Function1特征的情况下不是真的。

我们可以使用解决方法,

首先让我们定义可以重复使用的构建器,

Function1的构建器,

package lambdascala;

import scala.Function1;

public class Function1WithLambdaBuilder<P1, R> {

  public static interface Function1LambdaApply<P1, R> {
    R apply(P1 p1);
  }

  private Function1LambdaApply<P1, R> lambda;

  private Function1<P1, R> function;

  public Function1WithLambdaBuilder(Function1LambdaApply<P1, R> lambda) {
    this.lambda = lambda;
    this.function = new Function1<P1, R> () {
      @Override
      public R apply(P1 p1) {
        return Function1WithLambdaBuilder.this.lambda.apply(p1);
      }
    };
  }

  public Function1<P1, R> getFunction() {
    return this.function;
  }

}

Function2

的另一个构建器
package lambdascala;

import scala.Function2;

public class Function2WithLambdaBuilder<P1, P2, R> {

  public static interface Function2LambdaApply<P1, P2, R> {
    R apply(P1 p1, P2 p2);
  }

  private Function2LambdaApply<P1, P2, R> lambda;

  private Function2<P1, P2, R> function;

  public Function2WithLambdaBuilder(Function2LambdaApply<P1, P2, R> lambda) {
    this.lambda = lambda;
    this.function = new Function2<P1,P2, R> () {
      @Override
      public R apply(P1 p1, P2 p2) {
        return Function2WithLambdaBuilder.this.lambda.apply(p1, p2);
      }
    };
  }

  public Function2<P1, P2, R> getFunction() {
    return this.function;
  }

}

您可以按照相同的模式为更多FunctionN添加构建器。

现在我们可以使用这些构建器构建Function1Function2

import lambdascala.Function1WithLambdaBuilder;
import lambdascala.Function2WithLambdaBuilder;
import scala.Function1;
import scala.Function2;
import java.util.List;

public class LambdaTry {

  public static void main() {

    Function1<List<Long>, List<Long>> changeNothing =
      new Function1WithLambdaBuilder<List<Long>, List<Long>>(
        // your lambda
        (List<Long> list) -> list
      ).getFunction();

    Function1<Integer, Integer> add2 =
      new Function1WithLambdaBuilder<Integer, Integer>(
        // your lambda
        (Integer i) -> i + 2
      ).getFunction();

    Function2<Integer, Integer, Integer> add =
      new Function2WithLambdaBuilder<Integer, Integer, Integer>(
        // your lambda
        (Integer i, Integer j) -> i + j
      ).getFunction();

    System.out.println(add2.apply(12));

    System.out.println(add.apply(12, 24));

  }

}