当前位置:网站首页>Scala Either, Left And Right

Scala Either, Left And Right

2021-10-22 10:57:44 Bird's nest

Scala Medium Either Is an interesting class , It represents the value of one of two possible types . There is no intersection between these two values .
Either Abstract class , There are two concrete implementation classes : Left and Right.
Either It can be used as scala.Option Replacement , It can be used scala.util.Left Replace scala.None, use scala.Right Replace scala.Some.
It is generally used in practice scala.util.Left As Failure, and scala.util.Right As a success value .
Another similar class is scala.util.Try

for instance :

       
       
       
1
2
3
4
5
6
7
8
9
10
11
12
       
       
       
val in = Console.readLine( "Type Either a string or an Int: ")
val result: Either[String,Int] = try {
Right(in.toInt)
} catch {
case e: Exception =>
Left(in)
}
println( result match {
case Right(x) => "You passed me the Int: " + x + ", which I will increment. " + x + " + 1 = " + (x+ 1)
case Left(x) => "You passed me the String: " + x
})

If the entered value can be converted to Int type , Then the result result by Right(int), otherwise result by Left(String).
You can use match Processing results .

Either Type also provides projection (projection) operation . According to the type Left still Right Return different results .
for example , Use a function to convert Either Value of type , If the value is Left, application left Projection , And then call map Return the result of processing , And application right Projection just returns Left, Such as :

       
       
       
1
2
3
4
       
       
       
val l: Either[String, Int] = Left( "flower")
val r: Either[String, Int] = Right( 12)
l.left.map(_.size): Either[Int, Int] // Left(6)
l.right.map(_.toDouble): Either[String, Double] // Left("flower")

similarly , Yes Right Value for left Projection , Just go back to Right, Do not change , Only to right Projection works :

       
       
       
1
2
3
4
       
       
       
val l: Either[String, Int] = Left( "flower")
val r: Either[String, Int] = Right( 12)
r.left.map(_.size): Either[Int, Int] // Right(12)
r.right.map(_.toDouble): Either[String, Double] // Right(12.0)

Now that it's defined map operation , You can use for sentence :

       
       
       
1
       
       
       
for (s <- l.left) yield s.size // Left(6)

Either except left,right Outside projection , Some other methods are also provided :

  • fold: l.fold(x => x.size, y => y.toDouble);r.fold(x => x.size, y => y.toDouble)
  • swap: l.swap //Right(flower)
  • merge: l.merge == "flower"
  • joinLeft: LeftEither[Int, String], String).joinLeft
  • joinRight: Either[A, Either[A, C]]

stay Scala Use in Future, Often deal with Future The end result of , If you don't succeed , Or fail , Here we use Either:

       
       
       
1
2
3
4
5
6
7
       
       
       
val f: Future[List[String]] = future {
session.getRecentPosts
}
f onComplete {
case Right(posts) => for (post <- posts) render(post)
case Left(t) => render( "An error has occured: " + t.getMessage)
}

Mentioned earlier Try It's also two values ,Success and Failure, It can work with Either convert :

       
       
       
1
2
3
4
5
6
7
8
9
       
       
       
object Helper{
implicit class EitherPimp[L <: Throwable,R](e:Either[L,R]){
def toTry:Try[R] = e.fold(Failure(_), Success(_))
}
implicit class TryPimp[T](t:Try[T]){
def toEither:Either[Throwable,T] = t.transform(s => Success(Right(s)), f => Success(Left(f))).get
}
}

perhaps

       
       
       
1
2
3
4
5
6
7
8
9
10
11
12
13
14
       
       
       
import scala.util.{ Either, Failure, Left, Right, Success, Try }
implicit def eitherToTry[A <: Exception, B](either: Either[A, B]): Try[B] = {
either match {
case Right(obj) => Success(obj)
case Left(err) => Failure(err)
}
}
implicit def tryToEither[A](obj: Try[A]): Either[Throwable, A] = {
obj match {
case Success(something) => Right(something)
case Failure(err) => Left(err)
}

Reference documents

  1. http://www.scala-lang.org/files/archive/nightly/docs/library/index.html#scala.util.Either
  2. http://danielwestheide.com/blog/2013/01/02/the-neophytes-guide-to-scala-part-7-the-either-type.html
  3. http://stackoverflow.com/questions/22532357/either-to-try-and-visa-versa-in-scala

版权声明
本文为[Bird's nest]所创,转载请带上原文链接,感谢
https://chowdera.com/2021/10/20211009000611643t.html