I’m working my way through Programming in Scala, and though I’m tempted to look at things from the perspective of Python, I don’t want to program “Python in Scala.”
I’m not quite sure what to do as far as control flow goes: in Python, we use for x in some_iterable to death, and we love it. A very similar construct exists in Scala which Odersky calls a for expression, probably to distinguish it from the Java for loop. Also, Scala has a foreach attribute (I guess it would be an attribute, I don’t know enough about Scala to name it correctly) for iterable data types. It doesn’t seem like I can use foreach to do much more than call one function for each item in the container, though.
This leaves me with a few questions. First, are for expressions important/heavily used constructs in Scala like they are in Python, and second, when should I use foreach instead of a for expression (other than the obvious case of calling a function on each item of a container)?
I hope I’m not being terribly ambiguous or overbroad, but I’m just trying to grok some of the design/language fundamentals in Scala (which seems very cool so far).
python uses
forin list comprehensions and generator expressions. Those are very similar to the scalaforexpression:this is python
this is scala
Each construct can take a number of generators/iterators, apply filters expressions and yield a combined expression. In python the
(expr for v1 in gen1 if expr1 for v2 in gen2 if expr2)is roughly equivalent to:In scala
for (v1 <- gen1 if expr1; v2 <- gen2 if expr2) yield expris roughly equivalent to:If you love the python
for x in xssyntax, you’ll likely love the scalaforexpression.Scala has some additional syntax and translation twists. Syntax wise
forcan be used with braces so that you can put statements on separate lines. You can also perform value assignments.Also
v1 <- gen1really performs a matchcase v1 => gen1. If there is no match those elements are ignored from the iteration.I think
forhas an important place in the language. I can tell from the fact there is a whole chapter (23) about it in the book you’re reading!