[英]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
). (至少如果我没记错的话,静态方法是在RetryCode
上RetryCode
)。
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.