从Java调用Buffer上的foldLeft

时间:2012-07-25 22:11:30

标签: scala

我想从Java代码中调用scala foldLeft上的Buffer方法:

    List<Integer> javaList = new ArrayList<>();
    javaList.add(1);
    javaList.add(3);
    javaList.add(5);

    Buffer<Integer> scalaBuffer = JavaConversions.asScalaBuffer(javaList);

    scalaBuffer.foldLeft(0, new Function2<Integer, Integer, Integer>() {
        @Override
        public Integer apply(Integer accumulator, Integer element) {
            return carry + element;
        }
    });

但是我得到以下编译器错误:

Multiple markers at this line
- The type new Function2<Integer,Integer,Integer>(){} must implement the 
 inherited abstract method Function2<Integer,Integer,Integer>.apply$mcVDI
 $sp(double, int)
- The type new Function2<Integer,Integer,Integer>(){} must implement the 
 inherited abstract method Function2<Integer,Integer,Integer>.tupled$mcIDD$sp()
- The type new Function2<Integer,Integer,Integer>(){} must implement the 
 inherited abstract method Function2<Integer,Integer,Integer>.tupled$mcVJJ$sp()
- The type new Function2<Integer,Integer,Integer>(){} must implement the 
 inherited abstract method Function2<Integer,Integer,Integer>.apply$mcZDJ
 $sp(double, long)
    .
    .
    .

基本上,我必须实现一大堆我不感兴趣的方法。

是否有简单的解决方案从Java上调用monad上的foldLeft方法?

谢谢, 约翰

(使用Scala 2.10-M5和JDK 1.7)

2 个答案:

答案 0 :(得分:1)

根据this scala-lang thread,适当的行动方案可能是scala.runtime.AbstractFunction2而不是直接实施Function2

这个帖子在scala时间有点旧,但它可能指向一个解决方案。我承认我自己没有尝试过。

答案 1 :(得分:1)

您可以尝试扩展AbstractFunction2,而不是实施Function2

对于java编译器,scala traits只是接口,并且它无法自动让你实现那些在trait中不抽象的方法。仅查看接口,从java中可以看出所有方法都是抽象的。