任何时候你想要在数量方面做出通用的东西,无形的 https://github.com/milessabin/shapeless很可能有你需要的东西。在这种情况下,您可以编写以下内容:
import scala.util.control.NonFatal
import shapeless._, ops.function._
def safeify[F, A <: HList, R, O](f: F)(implicit
ftp: FnToProduct.Aux[F, A => R],
ffp: FnFromProduct[A => Either[Throwable, R]]
) = ffp((a: A) =>
try Right(ftp(f)(a)) catch {
case NonFatal(ex) => Left(ex)
}
)
现在假设我们有一个不安全的方法,如下所示:
def bad(s: String, i: Int) = s.toInt / i
我们可以将它包装起来:
scala> val better = safeify(bad _)
better: (String, Int) => Either[Throwable,Int] = <function2>
现在我们不必担心异常:
scala> better("1", 0)
res0: Either[Throwable,Int] = Left(ArithmeticException: / by zero)
scala> better("a", 1)
res1: Either[Throwable,Int] = Left(NumberFormatException: For input string: "a")
这适用于任何旧的FunctionN
.