16 Aug 2017

Scala Installation and sample example

Scala 0 Comment


Scala, short for Scalable Language, is a hybrid functional programming language. It was created by Martin Odersky in 2003. Scala smoothly integrates the features of object-oriented and functional languages. Scala is compiled to run on the Java Virtual Machine. Many existing companies, who depend on Java for business critical applications, are turning to Scala to boost their development productivity, applications scalability and overall reliability.

Why should we go for Scala?
We have some features in Scala to choose scala.

  1. Scala is Object Oriented
  2. Scala is Functional
  3. Scala is Statically typed
  4. Scala Runs on JVM
  5. Scala Execute java code
  6. Scala can do Concurrency & Synchronize processing

Scala Installation :
Step 1: Verify Your java Installation in our system.

purnaraot@nbmaclap24 ~ $ java -version
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)
purnaraot@nbmaclap24 ~ $

Step 2: Set Your JAVA Environment

  1. Add the below line of code under .bash_profile file in MAC and LINUX
    export JAVA_HOME /Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home
    export PATH=$JAVA_HOME/bin
  2. Append the String “C:\Program Files\Java\jdk1.8.0_131\bin” to the end of the system variable PATH in Windows.

Step 3: Install Scala:
You can download Scala from http://www.scala-lang.org/download/ , and downloaded scala-2.12.3.tgz version. Extract the tgz file and copy the path of bin and added it in bash_profile file, Like
export SCALA_HOME=/Users/purnaraot/Downloads/scala-2.12.3
export PATH=$SCALA_HOME/bin

Step 4: Check the scala installed or not:
Now We can enter command like “scala” in terminal, it is pointing to scala interpreter.

Sample examples:

Now you can type 5 * 6 in scala interpreter and enter now see the result below

We can observe above “res0” indicate default variable name and “Int” is type of data and 30 is result. We can use res0 in subsequent computations, see the below screenshot.

We can call the default methods on the result of variable, you can type res0 and followed by “.” And use tab completion, and see the available methods.

Declaring Values and Variables:
We have val and var are the datatypes in scala.
Instead of using the default names res0, res1, res2 etc… you can define our custom names by using var and val datatypes, see the below example “output” is the custom variable name.


  1. A Value declared with val is actually constant, we can’t change the content.
  2. If we declare with var we can able to change the value of variable.

we can use the script file to execute the example, for example copy the content into file with extension scala (sample.scala) and execute the file, see below.