I want to have some utilities to use and cleanup a resource, safely and unsafely, and clean up the resource after use, somewhat equivalent to a try/finally, allowing for cleanup 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 don't like
val tried: (R => Try[U]) = (r: R) => Try.apply(op(r))
It seems i'm missing some obvious composition function, but I can't see where. I tried
val tried: (R => Try[U]) = (Try.apply _).compose(op)
but that fails typecheck 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/doing wrong?