Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala's for-comprehensions: vital feature or syntactic sugar?

When I first started looking at Scala, I liked the look of for-comprehensions. They seemed to be a bit like the foreach loops I was used to from Java 5, but with functional restrictions and a lot of sweet syntactic niceness.

But as I've absorbed the Scala style, I find that every time I could use a for-comprension I'm using map, flatMap, filter, reduce and foreach instead. The intention of the code seems clearer to me that way, with fewer potential hidden surprises, and they're usually shorter code too.

As far as I'm aware, for-comprehensions are always compiled down into these methods anyway, so I'm wondering: what are they actually for? Am I missing some functional revalation (it wouldn't be the first time)? Do for-comprehensions do something the other features can't, or would at least be much clumsier at? Do they shine under a particular use case? Is it really just a matter of personal taste?

like image 964
Marcus Downing Avatar asked Sep 06 '09 15:09

Marcus Downing


People also ask

What operations is a for comprehension syntactic sugar for?

Finally, we discovered that a for-comprehension is just syntactic sugar for a sequence of calls to methods foreach, map, flatMap, and withFilter.

How Scala for comprehension works?

Scala offers a lightweight notation for expressing sequence comprehensions. Comprehensions have the form for (enumerators) yield e , where enumerators refers to a semicolon-separated list of enumerators. An enumerator is either a generator which introduces new variables, or it is a filter.

What is a for comprehension in Scala?

Comprehensions is a construct in Scala which allows us to evaluate certain expressions. The For Comprehension has the form for (enumerators) yield e , where enumerators refer to a semi-colon separated list of enumerators. An enumerator can either be a generator that iterates the list or a filter.


2 Answers

Please refer to this question. The short answer is that for-comprehensions can be more readable. In particular, if you have many nested generators, the actual scope of what you are doing becomes more clear, and you don't need huge indents.

like image 152
Daniel C. Sobral Avatar answered Sep 25 '22 08:09

Daniel C. Sobral


Another great use of for-comprehension is for internal DSL. ScalaQL is a great example of this. It can turn this

val underAge = for { 
  p <- Person 
  c <- Company 
  if p.company is c 
  if p.age < 14 
} yield p 

into this

SELECT p.* FROM people p JOIN companies c ON p.company_id = c.id WHERE p.age < 14 

and a whole lot more.

like image 45
Walter Chang Avatar answered Sep 26 '22 08:09

Walter Chang