& quot; Lambdifying&"Java中的scala函数 [英] "Lambdifying" scala Function in Java

查看:44
本文介绍了& quot; Lambdifying&"Java中的scala函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Java和Apache Spark(已在Scala中重写),面对旧的API方法( org.apache.spark.rdd.JdbcRDD 构造函数),其参数为AbstractFunction1:

Using Java and Apache Spark (that has been rewritten in Scala), faced with old API method (org.apache.spark.rdd.JdbcRDD constructor), that has AbstractFunction1 as it's argument:

abstract class AbstractFunction1[@scala.specialized -T1, @scala.specialized +R]() extends scala.AnyRef with scala.Function1[T1, R] {}

因为 AbstractFunction1 是一个抽象类,所以我不能使用Java8 lambdas,所以我决定包装

Because AbstractFunction1 is an abstract class, I cant use Java8 lambdas, so I decided to wrap scala.Function1 trait is the same with java.util.functions.Function but does't implements andThen and compose methods. As a result, i create thes interface:

import scala.Function1;

@FunctionalInterface
public interface Funct<T, R> extends Function1<T, R>, Serializable {

    @Override
    default <A> Function1<A, R> compose(Function1<A, T> before) {
        return null;
    }

    @Override
    default <A> Function1<T, A> andThen(Function1<R, A> g) {
        return null;
    }
}

IDE对此接口没有问题,但是在编译时会得到:

IDE has no problems with this interface, but while compiling, a get:

[ERROR] Funct is not a functional interface
[ERROR] multiple non-overriding abstract methods found in interface Funct

是否可以包装Scala的特征,以便我可以使用lambda作为方法:

Is it possible to wrap Scala's trait, that i can use lambdas for method:

void doMagic(scala.Function1<T,V> arg)

推荐答案

因此,您需要scala函数特征的函数接口版本,以便可以使用java8 lambda语法进行调用?您不必自己执行此操作.看看 https://github.com/scala/scala-java8-compat .它不像直接使用java8 lambda语法那样好,因为您仍然必须这样做

So you want a functional interface version of the scala function traits so you can call them with java8 lambda syntax? You don't have to do this yourself. Take a look at https://github.com/scala/scala-java8-compat . Its not quite as nice as directly using java8 lambda syntax, since you still have to do

import static scala.compat.java8.JFunction.*;
doMagic(func(x => ...));

代替

doMagic(x => ...);

但是在Scala 2.12中,一个大主题是Java8兼容性.scala FunctionX类本身将重做为SAM接口,因此,当scala 2.12发布时,您将能够执行后者.至少那是我上次检查的计划.

But in Scala 2.12 a big theme will be Java8 compatibility. The scala FunctionX classes themselves will be redone as SAM interfaces, so you will be able to do the latter when scala 2.12 comes out. At least that was the plan last time I checked.

这篇关于&amp; quot; Lambdifying&amp;&quot;Java中的scala函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆