0

I have a generic utility in scala to Retry a certain piece of code logic n number of times.

RetryCode.scala

object RetryCode {
    def retry[T](timesRetry: Int)(block: => T): T = {
        def doBlock() = block
        breakable {
            for (i <- 0 until timesRetry) {
                try {
                    ...
                    doBlock()
                } catch {
                    ...
                }
            }
        }
    }
}

Test Unit in Scala:

class RetryCodeTest {
    test("success on 1st retry") {
        var i = 0
        val result = retry(5) {
          i = i + 1
          i
        }
        assert(result==1)
    }
}

I'd like to extend this functionality to a Java program

private void myMethod(int x) {
    try {
        // Code block to Retry 10 times
        ...
    } catch(Exception ex) {
        System.out.println("Error: " + ex.getMessage());
    }
}

How do I send a block of Java 7 code to my RetryCode object in Scala?

5
  • create instance of Java class in the Scala class? call myMethod within the loop? Commented Sep 9, 2016 at 20:51
  • Unfortunately that's not an option as the Scala object is used frequently else where in Scala code base. Commented Sep 9, 2016 at 20:52
  • You don't; you do something with a lambda or an interface. Commented Sep 9, 2016 at 21:07
  • Lambda is not an option as it's Java 7 and not Java 8. Commented Sep 9, 2016 at 22:01
  • I'd overload the retry() method in Scala with one that takes a Java Callable, and passes it to your real retry method. Then in your Java you could create an anonymous Callable (or a lamda expression in Java 8). Something along those lines. Commented Sep 10, 2016 at 4:36

2 Answers 2

1

The signature of retry which Java sees is <T> T retry(int timesRetry, scala.Function0<T> block). So you need to instantiate a Function0, but extending it directly in Java won't work; instead you want

RetryCode.retry(10, new scala.runtime.AbstractFunction0<Integer> {
  @Override
  public Integer apply() { return something; }
});

(At least if I remember correctly and the static method is generated on RetryCode).

Note that in general you can't just assume a Scala API will be reasonably callable from Java; you may need to write a wrapper for it (in Scala).

Sign up to request clarification or add additional context in comments.

1 Comment

Unsure about this as things get quickly complicated with multiple arguments but +1 for the effort!
0

I rewrote my Java 7 program in Scala.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.