Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a Scala function in Java

I'm trying to implement a scala function object (specifically - to use with apache spark)

the equivalent java type is scala.Function0 (for a parameter less function)

besides the method that implements the business logic apply(), I see that I have to implement several other methods.

Simple googling the method names didn't help (I saw reference regarding a tag method which should be implemented - but the method name here are different.

Here is the code with those methods (with empty implementation).

    private static class functionObject implements Function0<Integer>{

    @Override
    public Integer apply() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public byte apply$mcB$sp() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public char apply$mcC$sp() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public double apply$mcD$sp() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public float apply$mcF$sp() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public int apply$mcI$sp() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public long apply$mcJ$sp() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public short apply$mcS$sp() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void apply$mcV$sp() {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean apply$mcZ$sp() {
        // TODO Auto-generated method stub
        return false;
    }

}

What are these methods? how are they supposed to be implemented? is there a cleaner solution that adding these to any class?

like image 444
Ophir Yoktan Avatar asked Sep 02 '14 12:09

Ophir Yoktan


1 Answers

Scalas FunctionX interfaces are traits, whose type parameters are specialized. Because specialization is done by scalac and therefore can't be done by javac you have to implement everything related to specialization by yourself.

Scala provides the abstract classes AbstractFunctionX, which can be easily implemented on the Java side:

// example Int => Int function
class Z extends scala.runtime.AbstractFunction1<Integer, Integer> {
  public Integer apply(Integer i) {
    return i;
  }
}
like image 109
kiritsuku Avatar answered Oct 08 '22 11:10

kiritsuku