Scala Sugar - Iteration

In this second installment of Scala Sugar, lets put the lists that we created in the previous post to use.

How do we typically interact with lists when writing non-trivial programs? We iterate over them! With that being said, lets explore how iteration in Scala compares with iteration in Java.

Taking the lists in the previous post in to account, lets assign ourselves a task of iterating over each element in the list and converting them to uppercase.

First, we all know how to do this in Java using a standard for each loop:

(String s : l) { System.out.print(s.toUpperCase()); }

There are so many different ways to iterate in Scala, thus we are only going to talk about the most trivial ways.

for (s \<- l) print (s.toUpperCase())

-or-

l.map(_.toUpperCase()).foreach(printf("%s", _))

Download Source: simpleLists.scala

As you can see, you can loop in Scala the same way that you do in Java, namely, with a for each loop. There is nothing special about that.

The second loop is written in more a functional paradigm, as it uses the Scala map function. It allows you to iterate over the list without having to know anything about the details of the iteration itself. With Scala you are working at a much higher level. If we look at the Scala map function, it takes in a function as an argument, in this case the function is “toUpperCase()”. The map function then applies this function to all of the elements in the List, thus you don’t have to worry about the actual iteration logic. In this scenario, all the caller needs to worry about is that they have a List of elements, and they want some function f applied to all of them.

You can chain functions together on a List. In this case, we changed a foreach to the end of the map. If we were to describe the what is going on in plain english, it would sound something like, take all the elements of l, apply “toUpperCase” to all of them, then for each of them, print them.

The final interesting thing to notice in the above line of code is the “_” placeholder syntax. It looks strange to have a “_” there as part of the code, but all it is doing is acting as a placeholder for the function. It simply represents the current element of the List being operated on. Even though there are two “_“‘s in this example, they are completely independent of each other. The placeholder is a very powerful advanced concept in Scala and this example barely touches the surface of its usage. We will talk more about it in a dedicated post.

As you can see, Scala supports both the “Java” way of iterating and a pure functional way. Again, this example is just one of the many different techniques for iterating in Scala. In a future post we will look at other ways of iterating in Scala.

References

  • The code found in this post is hosted at github.com along with other sample Scala code.
comments powered by Disqus