撰写更好 [英] compose Try nicer
本文介绍了撰写更好的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望有一些实用程序可以安全和不安全地使用和清理资源,并在使用后清理资源,这在某种程度上等同于try / finally,即使操作抛出异常也允许清理。
我有
def withResource [R,U](create:=> ; R,cleanup:R => Unit)(op:R => U):U = {
val r =创建
val res = op(r)
cleanup(r )
res
}
def tryWithResource [R,U](create:=> R,cleanup:R => Unit)(op:R => U ):Try [U] = {
val尝试过:(R => Try [U])=(r:R)=> Try.apply(op(r))
withResource(create,cleanup)(tried)
}
但是我不喜欢
val try:(R => Try [U])= (r:R)=> Try.apply(op(r))
似乎我缺少一些明显的合成功能,但是我看不到哪里。我尝试了
val尝试了:(R => Try [U])=(Try.apply _)。compose(op )
但使用
<$ p进行类型检查失败$ p>
类型不匹配;发现
[错误]:R => U
[必需的] [错误]:R => =>没有尝试
[错误] val:(R => Try [U])=(Try.apply _)。compose(op)
我缺少什么/做错什么了?
解决方案
您可以使用一种类型限制将您传递给 Try.apply
的参数限制为 U
的参数:
val尝试=(Try.apply(_:U))撰写op
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?
解决方案
You can use a type ascription to limit the parameter you pass to Try.apply
to U
:
val tried = (Try.apply(_: U)) compose op
这篇关于撰写更好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文