Search code examples
scalathunk

Scala Lifting to a thunk


I have a function that wraps the result of another function in a Promise. I wanted to promote this into a lift function so that I could sort of re-use it elsewhere. Here are the original definitions:

val abc = Promise[MyType]()
try {
  val suck = abc.success(someOtherFunction(intParam1, intParam2))
} catch {
  case ex: Exception => p.failure(ex)
}

So what I eventually did was the following:

def myLiftFunc[X](x: X) (op: => X): Promise[X] = {
  val p = Promise[X]()

  try {
    p.success(op)
  } catch {
    case NonFatal(ex) =>
    p.failure(ex)
  }
  p
}

How can I re-use this? I mean, the second argument that I pass in should be a thunk so that I could just pass in any function body irrespective of the parameters that function body would require!

When I call the lifted function as:

myLiftFunc(someOtherFunction(intParam1, intParam2))

This is of type Int => Promise[Int], where the someOtherFunction returns an Int. I just want Promise[Int] when I call myLiftFunc!


Solution

  • You might be interested in the Promise.fromTry method. That method uses the Try idiom from scala.util, which is a useful structure that allows you to treat a try...catch statement more like a traditional constructs:

    Promise.fromTry { Try { someOtherFunction(intParam1, intParam2) } }
    

    If you wanted to right your own helper (so that the Try part is unnecessary, you could try something like:

    def myLiftFunc[X](op: => X): Promise[X] = Promise.fromTry(Try(op))
    

    This would allow you to do:

    myLiftFunc { /*arbitrary logic*/ }
    myLiftFunc(1 + 4).future.value.get //Success(5)
    myLiftFunc(1/0).future.value.get //Failure(java.lang.ArithmeticException: / by zero)