在Scala中,是否有一个预先存在的库函数用于将异常转换为选项?

发布于 2024-12-13 18:07:54 字数 370 浏览 0 评论 0原文

这基本上是包装 java 工厂方法,如果无法根据输入创建项目,这些方法会抛出异常。我正在基础库中寻找类似的内容:

 def exceptionToOption[A](f: => A):Option[A] ={
    try{
      Some(f)}
    catch{
      case e:Exception => None}
  }

用法:

val id:Option[UUID] = exceptionToOption(UUID.fromString("this will produce None"))

我知道我可以自己编写,但我想检查我没有重新发明轮子。

This is basically to wrap java factory methods which throw exceptions if the item can't be created based on the inputs. I'm looking for something in the base library like:

 def exceptionToOption[A](f: => A):Option[A] ={
    try{
      Some(f)}
    catch{
      case e:Exception => None}
  }

Usage:

val id:Option[UUID] = exceptionToOption(UUID.fromString("this will produce None"))

I know I can write my own but I want to check I am not re-inventing the wheel.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

谜泪 2024-12-20 18:07:54

使用 scala.util.control.Exception< /a>:

import scala.util.control.Exception._

allCatch opt f

你可以让它变得更复杂。例如,要仅捕获算术异常并检索异常:

scala> catching(classOf[ArithmeticException]) either (2 / 0)
res5: Either[Throwable,Int] = Left(java.lang.ArithmeticException: / by zero)

Use scala.util.control.Exception:

import scala.util.control.Exception._

allCatch opt f

And you can make it more sophisticated. For example, to catch only arithmetic exceptions and retrieve the exception:

scala> catching(classOf[ArithmeticException]) either (2 / 0)
res5: Either[Throwable,Int] = Left(java.lang.ArithmeticException: / by zero)
人间☆小暴躁 2024-12-20 18:07:54

是的,您可以查看 scala.util.control.Exception 对象。特别是 allCatch 函数。

Yes, you can take a look to the scala.util.control.Exception object. Especially, the allCatch function.

ら栖息 2024-12-20 18:07:54

从 scala 2.10 开始,您可以在 scala 中运行代码(例如工厂方法) .util.Try ,然后使用 toOption 将其转换:

import scala.util.Try
Try("foo".toInt).toOption  // None
Try("7".toInt).toOption    // Some(7)

或翻译为原始示例:

val id: Option[UUID] = Try(UUID.fromString("this will produce None")).toOption

As of scala 2.10, you can run your code (e.g. factory method) in a scala.util.Try and then convert it with toOption:

import scala.util.Try
Try("foo".toInt).toOption  // None
Try("7".toInt).toOption    // Some(7)

Or translated to your original example:

val id: Option[UUID] = Try(UUID.fromString("this will produce None")).toOption
你是年少的欢喜 2024-12-20 18:07:54

Scalaz 提供验证[+E, +A ]Either 类似。

val result: Validation[Throwable, Something] = ...

result match {
  case Success(x) => ...
  case Failure(x) => ...
}

Scalaz provides Validation[+E, +A] which is similar to Either.

val result: Validation[Throwable, Something] = ...

result match {
  case Success(x) => ...
  case Failure(x) => ...
}
雨后彩虹 2024-12-20 18:07:54

我在现代计算机中使用基于信号和非信号 NaN 的模式。 NaN 表示非数字。除以零 (fp) 会产生 NaN。 sNaN 抛出异常,非信号 NaN 仅作为结果提供,对结果的任何未来计算也会生成 NaN。 Evaluate 是信号传递,TryEvaluate 是非信号传递。

这里,Ctx=Context[I,R] 是一个上下文块,保存函数的输入 [I]、结果[R] 和异常。都是选项。上下文的更新方法是复制更新。不是变异更新。超级特征仅评估一个或多个函数,将更新的上下文传递给下一个函数。如果发生异常,主评估函数将返回上下文(跳过评估)。 Context[I,R]具有将(I=>R)转换为(Context[I,R]=>Context[I,R])的函数。因此,普通函数可以轻松转换为基于上下文的函数。

正如您所看到的,没有太多代码。这些特征就在我的实用程序包中,消费者几乎不需要任何代码就可以使用。使用库会增加所涉及工作的大量开销。

我将它用于我所有的解析器。基于 X-Path 的解析器仅调用一系列子解析器。因此就有了evaluate(Seq)方法。注意:我不喜欢方法。我倾向于尽可能使用函数。

哎呀,我想我上次发布的垃圾。这是 github 参考。
https://github.com/tyohDeveloper/acme/tree/master/ src/acme/util

I use a pattern based on signaling and non-signally NaNs in modern computers. NaN means non-a-number. Division by zero (fp) creates a NaN. sNaNs throw exceptions, non-signaling NaNs are just provided as a result, any future computation on the result also generates a NaN. Evaluate is signalling, TryEvaluate is non-signaling.

Here, Ctx=Context[I,R] is a context block that holds the function's input [I], result[R], and an exception. All are Options. The update method on the context is a copy-update. Not a mutating update. The super-trait just evaluates one or more functions, passing the updated context to the next function. The main evaluate function returns the context if an exception is held (skipping the evaluation). Context[I,R] has a function that translates a (I=>R) into a (Context[I,R]=>Context[I,R]). So a normal function can easily be converted into a context based function.

As you can see, there isn't much code. The traits are just in my utility package and can be used with almost no code by the consumer. Using a library adds to much overhead for the work involved.

I use this for all of my parsers. X-Path based parsers just call a sequence of sub-parsers. Hence the evaluate(Seq) method. Note: I dislike methods. I tend to use functions where I can.

Oops, I think I posted garbage the last time. Here is a github reference.
https://github.com/tyohDeveloper/acme/tree/master/src/acme/util

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文