1/8/08

Playing with SCALA: interoperation with Java

I'm toying with the Scala language and it looks like what the future Java could be (or a great candidate at least).
It feels like at the sweet spot between OO and functional paradigms.
It has first order functions, closures, comprehensions, type inference, mixing composition, Erlang-style concurrency, pattern matching, and more interesting stuff that makes coding easier and concise.
And the best thing is it compiles to .class files so it integrates seamlessly with Java: you have all your Java libraries when programming in Scala and you can call your Scala classes from your Java code as just another java class.
Of course, I'm not aware of anybody using it in a production environment, but looks VERY promising.
Having this kind of language makes less necessary to "bolt-in" those features in the core Java language.

So I installed the eclipse plugin and started to play with it.

I knew you could use Java libraries in Scala (even you can use Hibernate !) , so I was interested in the opposite way: calling Scala code from Java.
I created a Scala project and copied the QuickSort implementation:
(I put it in an "object", the Scala's singleton)


object MyScalaObj {
  def sort(xs: Array[Int]): Array[Int] =
    if (xs.length <= 1) xs else { 

      val pivot = xs(xs.length / 2) Array.concat(sort(xs filter (pivot >)), xs filter (pivot ==), sort(xs filter (pivot <))) 
    } 
}

After the project is compiled, I created a Java project and used the output path of the Scala project as a library, and voila! I could access the Scala classes from my Java code (even with code-completion). So my Java class is:


public class PruebaJavaScalaInterop {

  /**
  * @param args
  */
  public static void main(String[] args) {
    int[] org={4,2,5,3,1,9};
    int[] res=MyScalaObj.sort(org);
    System.out.println("Org:");
    dumpArray(org);
    System.out.println("Res:");
    dumpArray(res);
  }

  public static void dumpArray(int[] arr){
    for (int i=0;i < arr.length; i++ )
      System.out.print(arr[i]+" ");
    }
  }
}


The nice thing is the complex algorithms can be coded concisely in Scala using a Functional paradigm, and be called seamlessly from plain Java code.
I still need to learn more about it, but the possibilities seems very interesting, don't you think?
Post a Comment