尝试更好

compose Try nicer

我想要一些实用程序来安全和不安全地使用和清理资源,并在使用后清理资源,有点等同于 try/finally,即使操作抛出异常也允许清理.

我有

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)
}

但我不喜欢

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

我似乎缺少一些明显的合成功能,但我看不到在哪里。我试过了

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

但是

类型检查失败
type mismatch;
[error]  found   : R => U
[error]  required: R => => Nothing
[error]     val tried: (R => Try[U]) = (Try.apply _).compose(op)

我missing/doing哪里错了?

你可以直接使用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

您可以使用类型归属将传递给 Try.apply 的参数限制为 U :

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