Thursday, March 15, 2012

Getting Started with Scala

I started my learning by doing fresh eclipse 3.6 + Scala 2.9 build setup. Setup failed first time but second time I was able to create sample project and run few sample programs. Scala IDE download link is mentioned in references link at the bottom of this post. Now it is time to take deep dive into Scala world!

 Why Scala? Scala is a SCAlable LAnguage.

Scala is a functional-object hybrid language with several powerful factors working in its favor:
1.    Scala compiles to Java byte code, meaning it runs on the JVM. In addition to enabling you to continue leveraging the rich Java open-source ecosystem, Scala can be integrated into an existing IT environment with zero migration effort.
2.    Scala is based on the functional principles of Haskell and ML, yet still borrows heavily from the familiar object-oriented concepts Java programmers love. As a result, it can blend the best of both worlds into a whole that offers significant benefit without sacrificing the familiarity we've come to depend on.
Learning a new programming language is always a daunting task, particularly for one with an entirely new mindset on approaching problems, such as the functional approach that Scala embraces, and even more so when it is hybridized with another approach, such as how Scala melds object-orientation with functional concepts. Learning Scala requires time, and with that commitment looming over your already busy schedule, you may not be able to identify the return on your investment at first blush. Let me assure you, Scala provides a number of intriguing features, many of which will be covered in future pieces in this series. Following is a partial list to help you see the benefits of tackling this language. With Scala, you'll be able to:
•    Create internal DSLs (think Ruby), thanks to Scala's flexibility regarding identifiers.
•    Create highly scalable, concurrent data processors, thanks to Scala's immutable-state-by-default stance.
•    Reduce equivalent Java code by one-half or two-thirds, thanks to a variety of Scala's syntactic features such as closures and implicit definitions.
•    Take advantage of parallel hardware architectures (such as multi-core CPUs), thanks to Scala's encouragement of functional designs.
•    Understand larger code bases, thanks to Scala's simplification of certain type rules, in essence demanding that "everything is an object."

Certainly Scala represents a powerful, new way to look at programming; the fact that it compiles to and runs on the JVM just makes using it for "real work" all that much easier.

Functional concepts
Functional languages get their name from the concept that programs should behave like mathematical functions; in other words, given a set of inputs, a function should always return the same output. Not only does this mean that every function must return a value, but that functions must inherently carry no intrinsic state from one call to the next. This intrinsic notion of statelessness, carried over into the functional/object world to mean immutable objects by default, is a large part of why functional languages are being hailed as the great saviors of a madly concurrent world.
Unlike many of the dynamic languages that have recently begun to carve out a space of their own on the Java platform, Scala is statically typed, just as Java code is. Unlike the Java platform, however, Scala makes heavy use of type inferencing, meaning the compiler analyzes the code deeply to determine what type a particular value is, without programmer intervention. Type inferencing requires less redundant type code. For example, consider the Java code required to declare local variables and assign to them, shown in Listing 1:
Listing 1. The genius of javac (sigh)
class BrainDead {
  public static void main(String[] args) {
    String message = "Why does javac need to be told message is a String?" +
      "What else could it be if I'm assigning a String to it?";

let's take a look at what Scala can do.

Listing 2. Hello.Scala
object HelloWorld {
  def main(args: Array[String]): Unit = {
    System.out.println("Hello, Scala!")

How to Compile:
Compile this with scalac Hello.scala and then run the resulting code either by using the Scala launcher (scala HelloWorld) or by using the traditional Java launcher, taking care to include the Scala core library on the JVM's classpath (java -classpath %SCALA_HOME%\lib\scala-library.jar;. HelloWorld). Either way, the traditional greeting should appear.

Listing 2 explained:
Some elements in Listing 2 are surely familiar to you, but some very new elements are at work here too. For instance, starting with the familiar call to System.out.println demonstrates Scala's fidelity to the underlying Java platform. Scala goes to great lengths to make the full power of the Java platform available to Scala programs. (In fact, it will even allow a Scala type to inherit from a Java class, and vice versa, but more about that later.)

On the other hand, if you're observant, you'll have noticed the lack of a semicolon at the end of the System.out.println call; this is no typo. Unlike the Java platform, Scala does not require the semicolon to terminate a statement if the termination is obvious by the line ending. Semicolons are still supported, however, and are sometimes necessary if, for example, more than one statement appears on the same physical line. For the most part, the budding Scala programmer can simply leave off the semicolons, and the Scala compiler will gently remind him or her (usually with a glaring error message) when one is necessary.

Also, although this is a minor nit, Scala does not require the file containing a class definition to mirror the name of the class. Some will find this a refreshing change from Java programming; those who do not can continue to use the Java class-to-file naming convention without problem.

Key Points to remember about Scala:
1.    Scala makes it very easy to interact with Java code. All classes from the java.lang package are imported by default, while others need to be imported explicitly.
2.    static members (methods or fields) do not exist in Scala. Rather than defining static members, the Scala programmer declares these members in singleton objects.
3.    Scala Integration with Java, it should be noted that it is also possible to inherit from Java classes and implement Java interfaces directly in Scala.
4.    Functions as objects: It is possible to pass functions as arguments in Scala, to store them in variables, and to return them from other functions. This ability to manipulate functions as values is one of the cornerstone of a very interesting programming paradigm called functional programming.
5.    Classes in Scala are declared using a syntax which is close to Java’s syntax. One important difference is that classes in Scala can have parameters.
6.    All classes in Scala inherit from a super-class. When no super-class is specified, as in the Complex example of previous section, scala.AnyRef is implicitly used.

I am collecting Scala notes from whatever details I am able to find on internet. This is my first draft of the notes I am creating on Scala. I will fine tune this blog post once I collect all important features and components of Scala. This blog is still good resource for quick 2 minutes Scala reference.

Download & setup Scala IDE:

1 comment:

  1. Unfortunately that's all the information I can currently find about Scala programming here in Colorado. I'll try to keep updating this page as I learn information, particularly about Scala meetups in Colorado.