我的代碼中有許多用回傳型別定義的函式 asEither[Throwable, String]
并且所有函式都有一個 type 引數String
。我的代碼的三個代表函式定義為:
val f1 = (input: String) => {
/* Processing from the input using a library in my actual code returns a Either[Throwable, String] */
if (input == "a") Left(new Exception(input))
else Right("Success")
}
val f2 = (input: String) => {
if (input == "b") Left(new Exception(input))
else Right("Success")
}
val f3 = (input: String) => {
if (input == "c") Left(new Exception(input))
else Right("Success")
}
為了鏈接函式輸出,我正在撰寫如下代碼:
def x(input: String) = f1(input) match {
case Left(value) => Left(value)
case Right(_) => f2(input) match {
case Left(value) => Left(value)
case Right(_) => f3(input)
}
}
由于這只是三個函式,所以這可能看起來像一個短代碼。但是match
,我的代碼中發生了多個這樣的 es,所以這是一個很長的代碼。我希望避免這樣的鏈接。
我知道 Scala 有一種方法可以鏈接函式,例如f1.andThen(f2).andThen(f3)
,但問題是andThen
我們需要在每個函式中傳遞相同的引數,在這種情況下是input
. 但是我想鏈接這些函式,以便如果有Left
輸出,它不應該轉到下一個andThen
。
我相信這可以使用函式式編程來簡化,但我不知道從哪里開始。有沒有辦法使用 Scala 函式式編程來實作這一點?
uj5u.com熱心網友回復:
如果您的范圍內有貓,那么您需要做的就是:
import cats.syntax.all._
val functions: List[String => Either[Throwable, Unit]] = List(
// put your functions here.
)
val result: Either[Throwable, Unit] =
functions.traverse_(f => f(input))
否則,您可以使用以下方法模擬它:
val init: Either[Throwable, Unit] = Right(())
functions.foldLeft(init) {
case (acc, f) =>
acc.flatMap(_ => f(input))
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/508564.html
上一篇:sbt-protoc錯誤檔案不在使用--proto_path(或-I)指定的任何路徑中。您必須指定包含此檔案的--proto_path