在工作中,大多数人使用Java,而我正在使用Scala.我们决定在一个用Java编写的库中收集一些常用的类.现在我想在库中添加一些伪函数式编程,看看下面的内容:
Java的:
public interface Func<A, R> {
public R f(a A);
}
public AClass {
public <R> ArrayList<R> myMethod(
Func<String, R> func
) {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
在java中的用法:
AClass ac = new AClass();
ArrayList<String> al = ac.myMethod(
new Func<String, String> (
public String f(String s) {
return s + "!";
}
})
Run Code Online (Sandbox Code Playgroud)
上面并没有完全退出(从scala的角度来看,实际上更像是令人生畏).有没有办法召唤一些scala魔法,以便能够在scala中执行以下操作:
var ac = new ACLass
var al = ac.myMethod(str => str + "!") // alternative 1
al = ac.myMethod { case: str:String => str + "!" …Run Code Online (Sandbox Code Playgroud) 使用Java和Apache Spark(已经在Scala中重写),面对旧的API方法(org.apache.spark.rdd.JdbcRDD构造函数),它有AbstractFunction1作为它的参数:
abstract class AbstractFunction1[@scala.specialized -T1, @scala.specialized +R]() extends scala.AnyRef with scala.Function1[T1, R] {}
Run Code Online (Sandbox Code Playgroud)
因为AbstractFunction1是一个抽象类,我不能使用Java8 lambdas,所以我决定包装scala.Function1 trait是相同的java.util.functions.Function但不是实现andThen和compose方法.结果,我创建了thes接口:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
IDE对此接口没有任何问题,但在编译时,get:
[ERROR] Funct is not a functional interface
[ERROR] multiple non-overriding abstract methods found in …Run Code Online (Sandbox Code Playgroud)