由于您显然还没有足够的选择,另一种方法是使用ScalaUtils尝试方法。ScalaUtils 是一个非常小的、专注的库,您可能不介意将其添加为依赖项。尝试方法(在 org.scalautils 包对象中)将为您提供一个 Or 类型,您可以在该类型上调用 toEither。我首先建议使用 Try 执行此操作,这样您就不需要添加任何依赖项,但它似乎没有 toEither 方法,这让我感到惊讶。所以这就是 Or 的样子:
scala> import org.scalautils._
import org.scalautils._
scala> def foo(i: Int, s: String): String = { require(i >= 0); s * i }
foo: (i: Int, s: String)String
scala> def bar(b: Boolean, i: Int, s: String): Int = { require(i >= 0); if (b) s.length else i }
bar: (b: Boolean, i: Int, s: String)Int
scala> def foo2(i: Int, s: String) = attempt(foo(i, s)).toEither
foo2: (i: Int, s: String)Either[Throwable,String]
scala> def bar2(b: Boolean, i: Int, s: String) = attempt(bar(b, i, s)).toEither
bar2: (b: Boolean, i: Int, s: String)Either[Throwable,Int]
scala> foo2(2, "ho")
res10: Either[Throwable,String] = Right(hoho)
scala> foo2(-2, "ho")
res11: Either[Throwable,String] = Left(java.lang.IllegalArgumentException: requirement failed)
scala> bar2(true, 3, "ho")
res12: Either[Throwable,Int] = Right(2)
scala> bar2(false, 3, "ho")
res13: Either[Throwable,Int] = Right(3)
scala> bar2(false, -3, "ho")
res14: Either[Throwable,Int] = Left(java.lang.IllegalArgumentException: requirement failed)
抱歉,我最初错过了您想要一种方法。我可能会像 noziar 建议的那样超载:
scala> :paste
// Entering paste mode (ctrl-D to finish)
def safely[A, B, C](f: (A, B) => C): (A, B) => Either[Throwable, C] = (a: A, b: B) => attempt(f(a, b)).toEither
def safely[A, B, C, D](f: (A, B, C) => D): (A, B, C) => Either[Throwable, D] = (a: A, b: B, c: C) => attempt(f(a, b, c)).toEither
// Exiting paste mode, now interpreting.
safely: [A, B, C](f: (A, B) => C)(A, B) => Either[Throwable,C] <and> [A, B, C, D](f: (A, B, C) => D)(A, B, C) => Either[Throwable,D]
safely: [A, B, C](f: (A, B) => C)(A, B) => Either[Throwable,C] <and> [A, B, C, D](f: (A, B, C) => D)(A, B, C) => Either[Throwable,D]
scala> val foo3 = safely { foo _ }
foo3: (Int, String) => Either[Throwable,String] = <function2>
scala> val bar3 = safely { bar _ }
bar3: (Boolean, Int, String) => Either[Throwable,Int] = <function3>
scala> foo3(2, "ho")
res5: Either[Throwable,String] = Right(hoho)
scala> foo3(-2, "ho")
res6: Either[Throwable,String] = Left(java.lang.IllegalArgumentException: requirement failed)
scala> bar3(true, 3, "ho")
res7: Either[Throwable,Int] = Right(2)
scala> bar3(false, 3, "ho")
res8: Either[Throwable,Int] = Right(3)
scala> bar3(false, -3, "ho")
res9: Either[Throwable,Int] = Left(java.lang.IllegalArgumentException: requirement failed)
如果你想避免过载(和无形),那么另一种选择是磁铁图案。我相信这会让你找到一种安全的方法,但我认为重载会更简单。