gpt4 book ai didi

scala - 尝试更好

转载 作者:行者123 更新时间:2023-12-04 19:52:02 29 4
gpt4 key购买 nike

我想要一些实用程序来安全和不安全地使用和清理资源,并在使用后清理资源,有点等同于 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)

我错过了什么/做错了什么?

最佳答案

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

关于scala - 尝试更好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32966827/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com