KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I can use an = in a scala for-comprehension (as specified in section 6.19 of the SLS ) as follows: Option Suppose I have some function String => Option[Int] : scala> def intOpt(s: String) = try { Some(s.toInt) } catch { case _ => None } intOpt: (s: String)Option[Int] Then I can use it thus scala> for { | str <- Option("1") | i <- intOpt(str) | val j = i + 10 //Note use of = in generator | } | yield j res18: Option[Int] = Some(11) It was my understanding that this was essentially equivalent to: scala> Option("1") flatMap { str => intOpt(str) } map { i => i + 10 } map { j => j } res19: Option[Int] = Some(11) That is, the embedded generator was a way of injecting a map into a sequence of flatMap calls. So far so good. Either.RightProjection What I actually want to do : use a similar for-comprehension as the previous example using the Either monad . However, if we use it in a similar chain, but this time using the Either.RightProjection monad/functor, it doesn't work: scala> def intEither(s: String): Either[Throwable, Int] = | try { Right(s.toInt) } catch { case x => Left(x) } intEither: (s: String)Either[Throwable,Int] Then use: scala> for { | str <- Option("1").toRight(new Throwable()).right | i <- intEither(str).right //note the "right" projection is used | val j = i + 10 | } | yield j <console>:17: error: value map is not a member of Product with Serializable with Either[java.lang.Throwable,(Int, Int)] i <- intEither(str).right ^ </pre
Tags (comma-separated)
Save Edits
Cancel