私はScalaを起動し、JSONを処理するためにcirceを使用してプロジェクトを実行しています。
私は関数からのEitherリターンをたくさん目にしますが、それらすべてを処理するためのエレガントな方法を見つけられないようです。
たとえば、どちらか1つについては、次のスニペットのようにします。
if (responseJson.isRight) {
//do something
} else {
//do something else
}
しかし、それらがたくさんある場合はどうすればよいですか。たとえば、この例では、右側にまっすぐ進み、追加の検証を行う必要があると感じています。
ClassA(
someValue,
someValue,
someJson.hcursor.get[Double]("jsonKey1").right.get,
someJson.hcursor.get[Double]("jsonKey2").right.get,
someJson.hcursor.get[Double]("jsonKey3").right.get
)
複数のEither
オブジェクトがである場合にそれらのコンテンツを取得したいが、Right
それらが常にであるRight
かどうかわからない場合、複数のオブジェクトを(if-elsesなどの束で終わることなく)どのように処理する必要がありますか?
ケースクラスがあるとしましょう。
case class Demo(i: Int, s: String)
そして2つのどちらか、
val intEither: Either[Throwable, Int] = ???
val stringEither: Either[Throwable, Int] = ???
だから...最も基本的で明白なものから始めましょう、
val demoEither: Either[Throwable, Demo] =
intEither.flatMap(i =>
stringEither.map(s => Demo(i, s))
)
別の方法は、上記と同じことを行うことです-内包表記を使用することです、
val demoEither: Either[Throwable, Demo] =
for {
i <- intEither
s <- stringEither
} yield Demo(i, s)
ただし、monads
シーケンシャルです。つまり、最初の列Either
がaの場合Left
、2番目の列を見ることすらなくEither
、Left
。を取得するだけです。すべてのコンポーネントの検証情報を失いたくないので、これは検証にはほとんど望ましくありませんApplicative
。したがって、実際に必要なのはです。
そしてEither
ないApplicative
、あなたが使用する必要がありますcats
か、scalaz
またはこのため、独自のApplicativeを実装します。
catsは、Validated
検証されたコンポーネントのすべてのエラー情報を検証および保持できるようにする、この明確な目的のためのアプリケーションを提供します。
import cats.data._
import cats.implicits._
val intValidated: ValidatedNec[Throwable, Int] =
intEither.toValidatedNec
val stringValidated: ValidatedNec[Throwable, String] =
stringEither.toValidatedNec
val demoValidated: ValidatedNec[Throwable, Demo] =
(intValidated, stringValidated).mapN(Demo)
val demoEither: Either[List[Throwable], Demo] =
demoValidated.leftMap(errorNec => errorNec.toList)
または、これを1回だけ実行していて、に依存したくないcats
場合は、非常に用途の広いパターンマッチングを使用できます。
val demoEither: Either[List[Throwable], Demo] =
(intEither, stringEither) match {
case (Right(i), Right(s)) => Right(Demo(i, s))
case (Left(ti), Left(ts)) => Left(List(ti, ts))
case (Left(ti), _) => Left(List(ti))
case (_, Left(ts)) => Left(List(ts))
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加