Saturday, November 21, 2009

Programming in Scala – Part 2/?

In my previous post, we got started with simple Scala HelloWorld and moved on to write a bubble sort in Scala. This time let us look at some differences between a “var” and a “val” in scala. I hope you all know what “immutable” means – simply put Strings in Java/.NET are immutable. Anytime you modify a string, a new object of string is created – they cannot be changed in place. Well, in scala when you declare a variable with a “val” it would be immutable. Look at the following scala code.

object ValVar
{
def main(args: Array[String])
{
val immutableValue = 200
//immutableValue = 20 -> gives compiler error
var mutableValue = 200
mutableValue = 20
println("Immutable : "+immutableValue+"\n Mutable : "+mutableValue)
}
}


The decompiled program would look like shown in Java



import java.rmi.RemoteException;
import scala.Predef.;
import scala.ScalaObject;
import scala.ScalaObject.class;
import scala.StringBuilder;
import scala.runtime.BoxesRunTime;

public final class ValVar$
implements ScalaObject
{
public static final MODULE$;

static
{
new ();
}

public ValVar$()
{
MODULE$ = this;
}

public void main(String[] args) {
int immutableValue = 200;

int mutableValue = 200;
mutableValue = 20;
Predef..MODULE$.println(new StringBuilder().append("Immutable : ").
append(BoxesRunTime.boxToInteger(immutableValue)).
append("\n Mutable : ").
append(BoxesRunTime.boxToInteger(mutableValue)).toString());
}

public int $tag()
throws RemoteException
{
return ScalaObject.class.$tag(this);
}
}


Clearly, it does not look like "immutable" variables are declared final in the Java code. So it appears to me that Scala compiler does the job of making sure that the val'bles are immutable. For those curios to see what happens if you attempt to change a val'ble, see the screenshot below. Also it would be interesting to note that the scala compiler takes care of optimizing our string concatenation to make use of String builder, just like the javac!



image



So what did we learn?: If you wish to keep changing the values for a variable, then use "var" and if you want immutable variables, use "var".



Now that we know how to create both variables and val’bles, let us look at some fancy stuff that we could do with lists.



Whats your range?



Let us say, we need all odd numbers between 20 and 2000 which are divisible by both 5 and 7. If you were like me, we write the program to look like shown below.



object RangeAction1
{
def main(args: Array[String])
{
for(i <- 20 to 2000)
{
if( i % 5 == 0 && i % 7 == 0)
println(i)
}
}
}


Can we do any better? This looks too long now that I have been imagining things, increasing expectations about scala being so nice.



object RangeAction1
{
def main(args: Array[String])
{
(20 to 2000).filter(i=>i%5==0&&i%7==0).foreach(i=>println(i))
}
}


When we say “20 to 2000”, it returns a Range object. Look in the documentation to see what all magic could we do with range. Similarly if we were to work with lists, we could do something similar. Now to add 1 cent to the 3 cents we covered so far, what if i want the range to start with 20 and end with 2000 but increment by 10 and exclusive of 2000.




(20 until 2000 by 10).filter{i=> i % 5 == 0 & i % 7 == 0}.foreach{i=> println(i)}


Also, I wanted to be more like a regular programmer and put my closure inside {} instead of (). More fun later!

1 comment:

Dedi Sulaeman said...

hmm.. :) i just visit and read your articles.. and this's very helpfull for me. thanks.



visit me back okay..

nice blog.