I want to have some utilities for using and clearing the resource, safe and unsafe, and clearing the resource after use, which is somewhat equivalent to try / finally, which allows me to clear even if the operation throws an exception.
I have
def withResource[R, U](create: => R, cleanup: R => Unit)(op: R => U): U = {
val r = create
val res = op(r)
cleanup(r)
res
}
def tryWithResource[R, U](create: => R, cleanup: R => Unit)(op: R => U): Try[U] = {
val tried: (R => Try[U]) = (r: R) => Try.apply(op(r))
withResource(create, cleanup)(tried)
}
but I do not like
val tried: (R => Try[U]) = (r: R) => Try.apply(op(r))
I seem to be missing some obvious compositional function, but I can't see where. I tried
val tried: (R => Try[U]) = (Try.apply _).compose(op)
but with typecheck error with
type mismatch;
[error] found : R => U
[error] required: R => => Nothing
[error] val tried: (R => Try[U]) = (Try.apply _).compose(op)
What am I missing / is something wrong?
source
share