Scala loops

Today, I finally got to play with Scala. I’ve been using mainly Ruby (and loving it) for most of my projects but I promised myself (in one of my new year’s resolution) that I will learn a new programming language this year. So from time to time, I will sprinkle this blog with some Scala love.

Now, for some mandatory hello world program. Nah. The code below simply prints the arguments to your Scala program.

var i = 0
while (i < args.length) {
  println("hello " + args(i) + "!")
  i += 1
}

// Assuming you have saved the code in hello.scala, do the following to run the code:
// scala hello.scala arg1 arg2 arg3

The code above is an imperative style used normally in languages like C or C++. Most new programmers are exposed to this style.

Being a Ruby developer, I quickly wondered if there is something similar to “.each” method? Yes, there is.

args.foreach(arg => println(arg))
args.foreach(println)

Above is a functional style and is something you will be comfortable with as you improve your programming skill. In Scala, the second line is possible if the function accepts a single argument.

Since ‘println’ is just a function, you could just replace it with your own function.

def printer(x: String) = {
  println(x.toUpperCase)
}

args.foreach(arg => printer(arg))

Yes, you guessed right. You can also define anonymous function.

args.foreach(arg => { println(arg.toUpperCase) })

When I first heard that Scala is somewhat related to Java, my first thought was it is going to be another verbose language. Well, I was wrong🙂 It appears to be a fun and powerful language worth learning.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s