简体   繁体   English

将代码块从Java传递到Scala对象

[英]Passing a block of code from Java to a Scala object

I have a generic utility in scala to Retry a certain piece of code logic n number of times. 我在scala有一个通用实用程序,可以重试某段代码逻辑n次。

RetryCode.scala 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 : 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 我想将此功能扩展到Java程序

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 ? 如何将Java 7代码块发送到Scala RetryCode对象?

The signature of retry which Java sees is <T> T retry(int timesRetry, scala.Function0<T> block) . Java看到的retry的签名是<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; 因此,您需要实例化一个Function0 ,但是直接在Java中对其进行扩展将无法正常工作。 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 ). (至少如果我没记错的话,静态方法是在RetryCodeRetryCode )。

Note that in general you can't just assume a Scala API will be reasonably callable from Java; 注意,总的来说,您不能仅仅假设可以从Java合理地调用Scala API。 you may need to write a wrapper for it (in Scala). 您可能需要为此编写一个包装器(在Scala中)。

我在Scala重写了Java 7程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM