Scala Lifting to a thunk -
i have function wraps result of function in promise. wanted promote lift function sort of re-use elsewhere. here original definitions:
val abc = promise[mytype]() try { val suck = abc.success(someotherfunction(intparam1, intparam2)) } catch { case ex: exception => p.failure(ex) }
so did 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 re-use this? mean, second argument pass in should thunk pass in function body irrespective of parameters function body require!
when call lifted function as:
myliftfunc(someotherfunction(intparam1, intparam2))
this of type int => promise[int]
, someotherfunction
returns int
. want promise[int]
when call myliftfunc
!
you might interested in promise.fromtry
method. method uses try
idiom scala.util
, useful structure allows treat try...catch
statement more traditional constructs:
promise.fromtry { try { someotherfunction(intparam1, intparam2) } }
if wanted right own helper (so try
part unnecessary, try like:
def myliftfunc[x](op: => x): promise[x] = promise.fromtry(try(op))
this allow do:
myliftfunc { /*arbitrary logic*/ } myliftfunc(1 + 4).future.value.get //success(5) myliftfunc(1/0).future.value.get //failure(java.lang.arithmeticexception: / zero)
Comments
Post a Comment