compose Try nicer

2019-07-10 07:49发布

问题:

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?

回答1:

You can use a type ascription to limit the parameter you pass to Try.apply to U :

val tried = (Try.apply(_: U)) compose op


回答2:

You can just use map

val tried: (R => Try[U]) = Try.apply(_).map(op)

http://www.scala-lang.org/files/archive/nightly/docs/library/index.html#scala.util.Try