5/20/2009

Small Taste of Scala

I just got a small taste of the power of Scala, and it was quite yummy.

It all started when I was looking for a way to convert a Java time stored in a database table into a readable date and time.  If I were to write a Java class, it would involve:

  • Create a Java source file to declare my class
    • Declare import for java.util.Calendar
    • Define a main function
      • Parse the arguments
      • Get a Calendar instance
      • Set the time on the Calendar instance
      • Print out the Date represented by the Calendar
  • Compile the Java source file
  • Run the main function on the class, passing in the appropriate argument

This seemed really time consuming and ridiculous considering how simple it should be to do this.  I’ve been spending alot of time in Python, and I would probably be able to do this from the Python REPL in a few (or 1) line of code.  So, I started looking at dynamic languages on top of the JVM.

I decided to give Scala a shot.  Scala has a REPL that comes with the SDK.  So, I downloaded it and fired it up.  I then had to figure out how to write my code.

I’ll be honest – I didn’t read the manual and as a result, I don’t know much about Scala.  I just wanted to do something really simple.  So, I noticed on the Scala site that “Code Examples” was one of the main navigation options.  I looked at the Simple Examples and figured out how to call Java classes.  Looked pretty simple.

I fired up Scala’s REPL, and defined a function:

def convertTime(time: Long) {    val cal = java.util.Calendar.getInstance()    cal.setTimeInMillis(time)    println(cal.getTime())}


The function is pretty simple.  It just takes a Long time in milliseconds and prints out the corresponding String representation of that time value.  Once this was defined, I could call the function with the values from my database table and figure out what Date value they represented:



scala> convertTime(1242942308240L)Thu May 21 16:45:08 CDT 2009


The entire sequence of events from start to finish probably took 10 minutes.  Yes – that’s much longer than if I had written a simple Java class.  However, I think it’s VERY impressive to go from 0 to Scala function with results in 10 minutes.  To me, this is a a testament to how approachable Scala is as a language.  Further, I am amazed at what a great job its implementers have done with creating a very “dynamic language” experience on top of the JVM. 



Now, if I only had more time to play with it…