使用Scala函数,而不是像匿名对象那样的Java回调
Java风格的匿名回调包含了相对较多的样板文件,阅读起来并不愉快。有这样的东西会很好使用Scala函数,而不是像匿名对象那样的Java回调,java,scala,callback,anonymous-function,Java,Scala,Callback,Anonymous Function,Java风格的匿名回调包含了相对较多的样板文件,阅读起来并不愉快。有这样的东西会很好 workExpression 而不是 new SomeIF { @Override public someType doRun() { return workExpression } } 可能的解决方案是什么?一种可能的解决方案是使用隐式def将函数转换为传统回调类型。例如: // Required by some API trait Callable[A] { def
workExpression
而不是
new SomeIF {
@Override public someType doRun() {
return workExpression
}
}
可能的解决方案是什么?一种可能的解决方案是使用
隐式
def将函数转换为传统回调类型。例如:
// Required by some API
trait Callable[A] {
def call(): A
}
trait Processor[A,B] {
def process(a: A): B
}
// Our helper trait
trait MyImplicits {
implicit def funToCallable[A](f: () => A) = new Callable[A]() {
def call() = f()
}
implicit def funToProcessor[A,B](f: (A) => B) = new Processor[A,B]() {
def process(a: A) = f(a)
}
}
object App extends MyImplicits {
def main(args: Array[String]) {
// Traditional usage
runSomeCallable(new Callable[String]() {
def call() = "World"
})
runSomeProcessor(new Processor[String,Int] {
def process(a: String) = a.toInt * 2
})
// Usage with implicits
runSomeCallable(() => "Scala World")
runSomeProcessor((s: String) => s.toInt * 2)
}
// Methods defined by some foreign API
def runSomeCallable[A](callable: Callable[A]) {
println("Hello "+callable.call())
}
def runSomeProcessor(processor: Processor[String,Int]) {
println("From 1 to "+processor.process("1"))
}
}
因此,在使用某些代码时,可以为代码中使用的常见回调类型创建一个helper特性,以简化可读性。在Scala的未来版本中,可能会出现使用单个方法将闭包自动转换为接口的情况:这将避免当前需要的带有隐式的样板文件。@Arne:I编辑并添加了显式问题,但实际上这是可以推断出来的。我可以写一篇博客或其他文章,但我添加了这个(以及我找到的一个答案),目的是1)分享它2)从其他人那里收集更多关于它的知识。显然有人已经写了关于这个()的博客,但我在谷歌上找不到它,因为直到Alexey发了帖子,我才知道它叫SAM Close。