Passing a Java method-call to Scala class / method

I need to work with this huge monolithic code written in Java and has hundreds of repetitions of code like:

createButtonOne() {
    ... 
    public boolean pressed() {
        doSomething();
        return true;
    }
}

createButtonTwo() {
    ...
    public boolean pressed() {
        doAnotherThing();
        return true;
    }
}

The code is literally the same as the function being called, but rather annoying. Of course, I could outsource most of the methods, but it would cost me more time than using the best tools. Or so I thought.

I want to do the following:

ScalaButton buttonOne = new ScalaButton();
buttonOne.create("Label", Controller.doSomething());

ScalaButton buttonTwo = new ScalaButton();
buttonTwo.create("Label2", Controller.doAnotherThing());

So I created ScalaButton as follows:

class ScalaButton
{
    def create(label:String, action: () => Unit): Unit = 
    {
        val button:Button = singletonCreator.createButton(label);
        button.addListener(new InputListener()
        {
            override def pressed(...)
            {
                action()
                true
            }
        }
}

The problem is that I never made this call with Java and it says

void found, scala.Function0 required

So, I wonder if it is possible to transfer the call of the java method to Scala this (or other) way? I did not work with Java after a few months and never used it with Scala in this way ...

+4
1

, ScalaButton.create, , void.

Scala Java, - - AbstractFunction0<BoxedUnit>, () => Unit.

:

import scala.AbstractFunction0
import scala.runtime.BoxedUnit

:

buttonOne.create("Label", new AbstractFunction0<BoxedUnit>() {
    @Override
    public BoxedUnit apply() {
        Controller.doSomething()
        return BoxedUnit.UNIT;
    }
});

Function0<BoxedUnit>, - Java.

, . Java 8, .

, :

private static Function0<BoxedUnit> getBoxedUnitFunction0(Runnable f) {
    return new AbstractFunction0<BoxedUnit>() {

            @Override
            public BoxedUnit apply() {
                f.run();
                return BoxedUnit.UNIT;
            }
        };
}

import scala.Function0 - , . :

buttonOne.create("Label", getBoxedUnitFunction0(Controller::doSomething));
+2

All Articles