Scala Sugar - Lists

If I want to become a real Scala Ninja, I am going to have change the way I think about coding. For the past 10 years I have been programming primarily using the object oriented paradigm. Although Scala supports pure object oriented programming, it is my desire to learn to program in Scala in a complete functional paradigm.

Of course, learning a new programming paradigm is not going to happen over night, it is going to take a bit of time. Over the course of the next few months, I am going to be posting a series of posts documenting my progress learning Scala. They will be written from the perspective of a “hardcore” Java programmer being enlightened by a sweet new language. I will write about all of the “sugar” Scala has to offer a Java programmer, and that is how I came up with title “Scala Sugar”.

In this first installment of Scala Sugar lets discuss one of the most fundamental concepts required to write any non-trivial program, namely Lists. For the longest time, Lists in Java didn’t bother me at all, as they seemed “normal” to me. That was until I was introduced to dynamic languages a few years back. Now, Lists in Java seem extremely verbose to me as I wonder why in Java you can’t just create and populate a list with a single line of code. Lets look at our first Java vs Scala comparison.

Lets create a trivial list of three lowercase strings.

import java.util.ArrayList;
import java.util.List;
List<String> l = new ArrayList<String>();
l.add("a");
l.add("b");
l.add("c");

In Java it takes a minimum of 6 lines of code to declare a list of 3 strings! Now lets declare the same list in Scala.

val l = List("a", "b", "c")

Thats it, one line of code! The most important things to pay attention to are:

  • No need to import List in Scala, as most fundamental classes are imported by default in Scala
  • You do not have to give ‘l’ a type in Scala. Scala uses Type inference which means that it can infer its type from the object it is pointing to. It is important to realize that Scala is statically typed, it just doesn’t require you to type your variables when you define them. The compiler is smart enough to figure it out.
  • You can construct a list with elements in Scala, no need to “add” each element separately.

Even in this trivial example, you can start to see how clean and concise Scala is.

In my next post we will explore different ways to iterate over the lists.

References

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