简体   繁体   中英

Convert Either[A, B] to Option[A] where Left becomes Some

I would like to convert an Either[A, B] to an option, such that if Either is Left it is Some[A] , and if it is Right it is None .

So far I've come up with

either.swap.map(Some(_)).getOrElse(None)

which is a bit of a mouthful.

and

either match { 
  case Left(value) => Some(value)
  case Right(_) => None
}

which is fine, but ideally I would like to know if there's a more idiomatic way using methods rather than an explicit match.

Converting Luis's comment to answer we have

either.swap.toOption

For example

val either: Either[String, Int] = Left("Boom")
either.toOption
either.swap.toOption 

outputs

res0: Option[Int] = None
res1: Option[String] = Some(Boom)

where we note either.toOption returns Option[Int] whilst either.swap.toOption returns Option[String] .

Apologies for copying in Luis' comment, but IMO it is useful enough to be posted as an answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM