Scala's Option.fold is a bit nasty to use sometimes because type inference is not always great. Here is a stupid toy example:
val someValue: Option[String] = ???
val processed = someValue.fold[Either[Error, UserName]](
Left(Error("No user name given"))
)(
value => Right(UserName(value))
)
The [Either[Error, UserName]] on fold is necessary otherwise the scala compiler can not derive the type.
Here is a really small trick to avoid Option.fold when you need to convert an Option to an Either:
val someValue: Option[String] = ???
val processed = someValue
.toRight(left = Error("No user name given"))
.map(value => Right(UserName(value)))
Much nicer!
No comments:
Post a Comment