Getting the desugared part of a Scala for/comprehension expression?

As I already said in the other topic, scalac -print prints out scala code, not java. It translates all scala keywords that are not directly compatible with java to normal scala code. It is not possible to let the compiler translate only parts afaik. But basically a for-comprehension is always translated the same way. A … Read more

Method parameters validation in Scala, with for comprehension and monads

If you’re willing to use Scalaz, it has a handful of tools that make this kind of task more convenient, including a new Validation class and some useful right-biased type class instances for plain old scala.Either. I’ll give an example of each here. Accumulating errors with Validation First for our Scalaz imports (note that we … Read more

Using Eithers with Scala “for” syntax

It doesn’t work in scala 2.11 and earlier because Either is not a monad. Though there’s talk of right-biasing it, you can’t use it in a for-comprehension: you have to get a LeftProject or RightProjection, like below: for { foo <- Right[String,Int](1).right bar <- Left[String,Int](“nope”).right } yield (foo + bar) That returns Left(“nope”), by the … Read more

withFilter instead of filter

From the Scala docs: Note: the difference between c filter p and c withFilter p is that the former creates a new collection, whereas the latter only restricts the domain of subsequent map, flatMap, foreach, and withFilter operations. So filter will take the original collection and produce a new collection, but withFilter will non-strictly (i.e. … Read more

Composing Option with List in for-comprehension gives type mismatch depending on order

For comprehensions are converted into calls to the map or flatMap method. For example this one: for(x <- List(1) ; y <- List(1,2,3)) yield (x,y) becomes that: List(1).flatMap(x => List(1,2,3).map(y => (x,y))) Therefore, the first loop value (in this case, List(1)) will receive the flatMap method call. Since flatMap on a List returns another List, … Read more

Confused with the for-comprehension to flatMap/Map transformation

TL;DR go directly to the final example I’ll try and recap. Definitions The for comprehension is a syntax shortcut to combine flatMap and map in a way that’s easy to read and reason about. Let’s simplify things a bit and assume that every class that provides both aforementioned methods can be called a monad and … Read more