我希望有一些实用程序可以使用和清理资源,安全和不安全,并在使用后清理资源,有点相当于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)
}
Run Code Online (Sandbox Code Playgroud)
但我不喜欢
val tried: (R => Try[U]) = (r: R) => Try.apply(op(r))
Run Code Online (Sandbox Code Playgroud)
看来我缺少一些明显的构图功能,但我看不到哪里.我试过了
val tried: (R => Try[U]) = (Try.apply _).compose(op)
Run Code Online (Sandbox Code Playgroud)
但是这样做没有成功
type mismatch;
[error] found : R => U
[error] required: R => => Nothing
[error] val tried: (R => Try[U]) = (Try.apply _).compose(op)
Run Code Online (Sandbox Code Playgroud)
我错过了什么/做错了什么?
你可以使用 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
Run Code Online (Sandbox Code Playgroud)