2

Java-style anonymous callbacks include relatively much boilerplate and are not pleasing to read. It would be nice to have something like

workExpression

instead of

new SomeIF {
    @Override public someType doRun() {
        return workExpression
    }
}

What are the possible solutions?

2
  • @Arne: I edited and added explicit question, but implicitly it could have been inferred. I could write a blog entry or else, but I added this on SO (and one answer I found) in order to 1) share it 2) collect more knowledge on it from others. Commented Jul 13, 2011 at 12:08
  • Apparently someone already blogged about this (tikalk.com/incubator/blog/simulating-sam-closures-scala), but I couldn't find it in google as I didn't know it was called SAM Closure until Alexey's post. Commented Jul 13, 2011 at 12:13

2 Answers 2

7

A possible solution is using implicit defs for converting functions to the legacy callback types. For example:

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

}

Therefore when working with some code, one could create a helper trait for the common callback types used in that code to ease readability.

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

Comments

2

Automatic conversion of closures to interfaces with single methods may appear in a future version of Scala: http://www.scala-lang.org/node/8744 This would avoid the boilerplate with implicits which is currently necessary.

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.