If you're interested in functional programming, you might also want to checkout my second blog which i'm actively working on!!

Wednesday, November 25, 2009

Scala: the art of writing code consise

If you come from a java background you're bound to get rusty in programming imperative as opposed to functional. I'm actually familiar with both programming styles and it would be great to be able to use both mixed together.

Now let's take a look at a simple function which takes a list of numbers and returns the sum.

In java this might look like the snippet below:


Ok... i know what you're gonna say... Use the enhanced for loop...


Well... get ready for some SCALA versions of the same functionality

You can also use the placeholder syntax:

But SCALA promotes NOT using var's ...so let's try to even reduce this further:

Using placeholder syntax this becomes:


As you can see we managed to reduce the function to a body with 1 line of code...

Expect more SCALA examples to follow.

No comments:

Post a Comment