使用Scala函数而不是类似Java回调的匿名对象

ron*_*ron 2 java scala callback anonymous-function

Java风格的匿名回调包括相对多的样板,并且不能阅读.有类似的东西会很高兴

workExpression
Run Code Online (Sandbox Code Playgroud)

代替

new SomeIF {
    @Override public someType doRun() {
        return workExpression
    }
}
Run Code Online (Sandbox Code Playgroud)

有哪些可能的解决方案?

ron*_*ron 7

一种可能的解决方案是使用implicitdefs将函数转换为传统的回调类型.例如:

// 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"))
  }

}
Run Code Online (Sandbox Code Playgroud)

因此,在使用某些代码时,可以为该代码中使用的公共回调类型创建一个辅助特征,以提高可读性.