Simply Scala – foreach

In this post I just want to give a very small example of Scala’s conciseness. Since the program is the evolutionised version of Java, the code will be match against Java. The example given here is just in simply creating a List containing three values and then displaying each one of them.

Java code:

List<Integer> list = new ArrayList<Integer>(){{
 add(1);
 add(3);
 add(5);
}};
for (int l: list) {
  System.out.println(l);
}

Scala code:

// Initiate the list.
val l = List(1,3,5)

// For every item in the list, represented as 'n', display its value.
l.foreach { n =>
  println(n)
}

At a glance you can see that the latter is more concise than the former. But hey, it’s actually still a bit redundant. Why do we still need to redefine the variable inside the loop? The code can still be simplified a bit more.

// Initiate the list.
val l = List(1,3,5)

// Display every value inside the list.
l.foreach { println(_) }

Inside the for-loop bracket, Scala considers the underscore (_) as the active item of the list. But, seriously, do we even need the underscore? I mean, we just want to println the value for each item in the list, right? So…

// Initiate the list.
val l = List(1,3,5)

// Display every value inside the list.
l.foreach { println }

But… wait, for this example, we can actually remove the bracket since it’s just executing one line of code for each item (this also applies for the Java codes above, BTW). Also, Scala has a syntactic sugar that allows you to take out the dot(.) in calling an object’s method. So, let’s try to apply these into the code:

// Initiate the list.
val l = List(1,3,5)

// Display every value inside the list.
l foreach println

Oh gosh! it’s even simpler! It cannot possibly go much further than this, right? Well, not really. You can simplify the code above a bit more by inlining the List directly into the loop.

// Create a list and display each value.
List(1,3,5) foreach println

There you go. One line. And I would argue that it’s even more readable than the 1st one.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s