Scala - Introduction,Installation and Hello world program!!

Scala is a general-purpose next generation programming language that runs on Java Virtual Machine (JVM) and .NET platforms. On JVM it generates intermediate java byte code as Java and on .NET platform Common Language Runtime(CLR) byte code.It integrates both object-oriented and functional programming languages,enabling programmers to be more productive.

Features of Scala - next generation mixed paradigm programming language

  1. Statically types language - variable is bound to a particular type for its lifetime
  2. Mixed paradigm- object-oriented and functional programming
  3. A JVM and .NET language
  4. Scalable architectures and performance
  5. Elegant and succinct - Less code lines(Type less, Do more)
  6. Re-usability - Java library inbuilt support
Lets walk through Scala features in details and understand how it addresses the major needs of the modern development.
1. Statically typed language - Scala is a statically typed language. A variable is bound to a particular type for its lifetime.Its type can’t be changed and it can only reference type-compatible instances. Suppose, if a variable refers to a value of type A, you can’t assign a value of a different type B to it, unless B is a subtype of A, for some reasonable definition of “subtype.” Read Statically typed Versus Dynamically typed Languages
2. Mixed paradigm- object oriented and functional programming:- Scala supports both programming paradigms, it is one of those rare languages that successfully integrates both object-oriented and functional language features. In Scala, everything is an object. Scala does not have primitive types, instead, all numeric types are true objects.Scala does not support “static” or class-level members of types and it support singleton - One object creation is allowed. Similar to interfaces in Java, Scala has traits - it is used to define object types by specifying the signature of the supported methods and as contrast to Java, default implementation may be provided.
Scala fully supports functional programming (FP).FP simplifies certain design problems, like concurrency problem.“Pure” functional languages avoids the need for synchronization on shared access to mutable state because they don’t allow for any mutable state.Instead,theycommunicate by passing messages between concurrent, autonomous processes. Scala supports this model with its Actors library, but it allows for both mutable and immutable variables.
3. A JVM and .NET language:- Scala has both JVM and .NET version. Scala is known predominantly as JVM language - generating intermediate byte codes. However, .NET version of Scala generates Common Language Runtime(CLR) byte code and .NET version of Scala is not stable.
4. Scalable architectures and performance:- Scala provides four language mechanisms that promote scalable composition of systems and these language construct allows applications to be constructed from reusable “components” in a type-safe and succinct manner.
  • Explicit self types- to declare the type of the value this explicitly
  • Abstract type members and generics- built-in support for classes parametrized with types
  • Nested classes support 
  • Mixin Class Composition using trait- Scala makes it possible to reuse the new member definitions of a class (i.e. the delta in relationship to the superclass) in the definition of a new class. This is expressed as a mixin-class composition. 
5.Elegant and succinct - Less code lines:- Scala minimizes unnecessary syntax(verbose syntax used in Java) and makes Scala code as succinct as code in most dynamically typed languages.Scala has a built-in type inference mechanism which allows the programmer to omit certain type annotations.
6.Re-usability(Inbuilt support of Java library ):- As it is an JVM language, Scala code reuses java library easily and refrains developer from reinventing the wheel.

Why Scala is tempting among developer community:- It is like dynamically typed scripting language(due to its succinct syntax) and provides all the benefits of static typing, a modern object model, functional programming, and an advanced type system. Scala is a difficult language to master compare to Ruby,Java because it requires competency with OOP, FP, and static typing to use it most effectively.

Installation and write hello world program:- 

Prerequisites:- Java 5.0 and above should be installed(Set JAVA_HOME environment variable too.)
For Windows:-
1. Download Scala binary distribution and install it.
2. Add bin directory of Scala installation in PATH system variable, as shown below.

3.Test installation:- Go to command prompt and type scala -version and we should see something like this.
C:\Users\nranjan>scala -version Scala code runner version 2.11.7 -- Copyright 2002-2013, LAMP/EPFL

For Linux:-
Follow following steps and set-up Scala in Linux (Ubuntu 13.04).
1. Remove existing Scala library if exists.
sudo apt-get remove scala-library scala
2. Get .deb file for Scala
wget http://www.scala-lang.org/files/archive/scala-2.11.7.deb
3. Extract .deb distribution and install.
sudo dpkg -i scala-2.11.7.deb
4. Add Scala to your $PATH by adding this line to .profile inside your home directory
PATH="$PATH:/opt/scala/bin"
5. Test installation, execute scala -version it should prompt text similar as shown above(In windows installation).

Alternate approach for Linux (Ubuntu 13.04):- 1. Download scala distribution scala-2.11.7.tgz and place it under say /opt/scala.
2. Add Scala bin to your $PATH by adding following line to .bashrc file.
gedit ~/.bashrc
export PATH=$PATH:/opt/scala/bin
3. Test installation using command "scala -version". 

Write Hello world program in Scala :-
There are various ways to run Scala code. We will see two commonly used ways:-
1. Using Scala REPL- A command line interactive shell called as REPL(Read-Eval-Print-Loop). To start Scala REPL, open command prompt and simply type Scala.
2. Using Scala interpreter to run scala script - Write Scala code in a file and do compile followed by run the intermediate class file.
Hello world in REPL(Interactive mode):-
1. Open command prompt/terminal and type scala, press enter.
2. Scala interactive shell opens up, just type print ("Hello world!!") and in return shell will display Hello world!!.
zytham@ubuntu:~$ scala
Welcome to Scala version 2.11.7 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_60).
Type in expressions to have them evaluated.
Type :help for more information.
scala> print ("Hello world!!")
Hello world!!
Hello world program using scala Interpreter:- It is two stages process, first compile the Scala source code using Scala compiler and second run the compiled bytecode using Scala interpreter. Create a file Hello.scala and type following code lines in it.
object Hello {
     def main(args:Array[String]):Unit = {
       println("Hello, World!! ")
 }
}
Now compile the scala code and run using following commands(scalac for compiling and scala for running class file.).
zytham@ubuntu:~$ scalac Hello.scala
zytham@ubuntu:~$ scala Hello
Hello, World !!
Explanation:- In above code lines, an object Hello, Object is way scala represent the static members and inside it we have main method taking param as array of strings and returning Unit which is same as void in Java. scalac is counterpart of javac(compiling scala code) and scala is for java(run class file ).

Scala code lines without main method:- 

We can directly run scala code lines without main method and here we do not require two stage(compile and execute class file). Instead, we can directly execute file and internally it is compiled and executed. Create a new file HelloMSG.scala and paste following code lines in it.
/* Block comments:- Upper class does not contain main method */
class HelloMSG {
def sayHello(stringMsg: String) = {
 println(stringMsg);
 }
}
/*Instance of Upper*/
val up = new HelloMSG
Console.println(up.sayHello("Hello, Scala"))
Now run upperCase.scala using following command.
zytham@ubuntu:~$ scala HelloMSG.scala
Hello, Scala
()
Explanation:HelloMSG class begins with the class keyword and class body is inside { }. The method definition of sayHello starts with def followed by method_name and an argument list, the return type of the method (= sign is used in Scala because function is treated as value/object and semicolons, function return types, method arguments lists are sometimes omitted and = sign takes care of all these possible conditions). Method argument type is of String.In Scala,when explicit type information for variables is written in the code, these type annotations follow the colon after the item name. For calling this method, creates an instance of HelloMSG and calls sayHello mehtod with string parameter.
If we type scala on the command line without a file argument, the interpreter runs in interactive mode.If we give the command a scala source file argument, it compiles and runs the file as a script as shown above.

Scala in Eclipse:- 

Download eclipse for Scala and make sure JDK  6+ is available in your system. Download 32 bit version if you have 32 bit JDK and download 64 bit eclipse if 64 bit JDK installed. Refer this for more detail.

In next post we will explore more Scala language construct - Data types,Variable and Method declaration in Scala

1 Comments

Previous Post Next Post