in Research

From Java to Scala…

This week I have started a course about Scala teached by Martin Odersky (the creator of this programming language). The course is basically focused on Functional programming with Scala and it reminds me my first steps in this paradigm when I was student of Labra‘s course “Functional and Logic Programming” in which I learnt some portions of Prolog and Haskell.

After some years using Java and encouraged by Labra I enrolled in this new language (I had performed my first steps in Scala some time ago but without specific objectives). The learning methodology is very easy: you have to follow and watch some video lectures and after that you have some assingments to be completed in the a fixed schedule, if you complete all assignments you can obtain a certificate!

The purpose of this post is to show (my own experience) how the same function can be coded in Java or Scala (this is the typical example of moving from an imperative paradigm to a functional one). Imagine that you have to calculate the sum of an integer list (1, 3, 5)

  • In Java, you will use something like…
int sum = 0;
for (int i = 0; i<l.size();i++){
 sum = sum + l.get(i);
return sum;
  • In Scala, using a Java style…
  def sum(xs: List[Int]): Int = {
	var sum = 0
	for (x <- xs)
		sum = sum + x
	return sum
  • In Scala, using recursion and Java style…
def sum(xs: List[Int]): Int {
    if (xs.isEmpty) return 0
    else return xs.head + sum(xs.tail)
  • In Scala, using a more functional approach…
def sum(xs: List[Int]): Int = xs match{
    case _ if xs.isEmpty => 0
    case _ => xs.head + sum (xs.tail)
  • In Scala, pure functional approach
def sum(xs: List[Int]): Int = xs.foldLeft(0)(_+_)
This is only to demonstrate how a good use of tools and programming techniques can ease the coding!

Write a Comment


This site uses Akismet to reduce spam. Learn how your comment data is processed.