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

后端 未结 5 1792
南笙
南笙 2021-01-31 20:04

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 rest

5条回答
  •  别那么骄傲
    2021-01-31 20:06

    You are right. The for-comprehension is syntactic sugar. I believe the underlying methods are more succinct and easier to read, once you are used to them.

    Compare the following equivalent statements:

    1. for (i <- 1 to 100; if (i % 3 == 0)) yield Math.pow(i, 2)
    2. (1 to 100).filter(_ % 3 == 0).map(Math.pow(_, 2))
    

    In my opinion, the addition of the semicolon in #1 distracts from the sense that this is a single chained statement. There is also a sense that i is a var (is it 1, or is it 99, or something inbetween?) which detracts from an otherwise functional style.

    Option 2 is more evidently a chain of method calls on objects. Each link in the chain clearly stating its responsibility. There are no intermediate variables.

    Perhaps for comprehensions are included as a convenience for developers transitioning from Java. Regardless, which is chosen is a matter of style and preference.

提交回复
热议问题