Quick Scala Tutorial – Learn with Examples

1 Flares Twitter 0 Facebook 1 Google+ 0 Pin It Share 0 LinkedIn 0 Filament.io 1 Flares ×

This tutorial will help you learn Scala quickly. Adopts a practical approach to learning.

Task 1 : Install Scala and Configure It
Download Scala by visiting  http://www.scala-lang.org/downloads
Download the latest version. The version I used is 2.11.8.  That version is available here http://www.scala-lang.org/download/2.11.8.html

The installable is available in different forms, if you are using windows, you can use the msi (.msi) installer. If you don’t want to install, you can use the zip files. You can find the scala distribution in zip ,tar, rpm formats. ( just scroll down and look at the Other resources section). I am using the zip format.

download-scala

Task 2: Setting up the Environment Variables

Unzip scala-2.11.8.zip to the directory of your choice. I have extracted to E:\Apps\scala-2.11.8. For quick access, add scala and scalac to your path.

For example: Windows

%SCALA_HOME% =  E:\Apps\scala-2.11.8
%PATH% =  %PATH%;%SCALA_HOME%\bin

 

Scala-Home Environment Variable

 

Scala Path Variable

Start the Scala interpreter (aka the “REPL”) by launching scala. You should see the prompt:

scala>

This is called REPL (Read-Eval-Print Loop). You can type any Scala expression, and the result will be printed. This completes the setting up of scala.

You are now ready to learn scala.

Language Basics

Comments

// Single-line comments start with two forward slashes

/*
Multi-line comments, are like this
*/

Variables

Two types val and var. val is immutable and var is mutable. Once you define a val you cannot reassign another value to it.

Type inference

Scala is able to automatically infer types. For instance when you type val a = 10, scala interpreter is able to guess the type as Int.

If you wish to explicitly define the type you can use val a: Int = 10

Type scala in a command prompt and try out the below

You can see that scala has automatically inferred the type of val. For a it inferred as Int and b as Double.

End of Statement

You don’t have to put a ; to indicate the end of a statement. Scala will automatically use the new line to infer the end of a statement.

Types

Let us see the commonly used types in scala.  Most common types are Int, Double, Float, String, Boolean. This is are similar to the types found in other languages like Java.

Scala strings are enclosed in double quotes ( “hello all”)

Strings can be dynamically constructed using interpolation. Scala uses the prefix s for this.

Note that usage of s before the string. The dynamic variables are substituted using the ${variable} syntax.

Functions

In scala functions are defined like this def functionName ([list of parameters]) : [return type]
Typically in scala, there is no need to use the return keyword. The last expression in the method body is the default return value.

If the function is a simple and has got a single line then the { } can be omitted. The function can be implemented in a single line

def add(x: Int, y: Int): Int = x+y

Functions can also have default parameters.

def add(x:Int, y:Int = 2) = x+y

Here the second argument takes 2 as the default value.

add(2) will result in 4

add(2,10) will output 12

Anonymous Functions

You can use anonymous functions using the usual syntax (x: Type) => definition

This means a function that takes a single argument as input.  (x:Int) => x*x. When you run this in the scala prompt, you can see that scala assigns this function to a variable. It is this variable that is to be used to invoke the function. We can straightaway assign to the variable.

Data Structures 

Array

In scala the arrays are defined using the ‘ ( ‘ braces instead of the ‘ [ ‘ used in languages like Java.

Accessing the array elements also uses the normal brackets instead of the square brackets

fruits(2)

grapes

Map

Map is a collection of key value pair.

Set

A set doesn’t keep duplicate elements. It always contains only unique values.

Classes

Classes in scala are similar to classes in other languages like java. Hence the details are not elaborated in this tutorial. If interested, you can read about classes here http://docs.scala-lang.org/tutorials/tour/classes.html But there is a special type of class in scala called case classes and deserves special attention.

Case Classes

Offical definition of case class is “Case classes are regular classes which export their constructor parameters and which provide a recursive decomposition mechanism via pattern matching.” Let us look at this in detail

  • To facilitate the construction of case class instances, Scala does not require that the new primitive is used. One can simply use the class name as a function.
  • The primary purpose of case classes is to hold immutable data
  • Scala compiler generates an equals method for every case class
  • Getters are auto generated.
  • It is typically used to pass values from one part of program to another. Similar to the value object design pattern

Let us define a  case class.

case class Employee( name:String, id: Int, dept: String)

case class Contractor(name:String,id:Int,dept:String)

To create a new Employee ,  var emp = Employee(“john”,100,”IT”)

// To access the property

println(emp.name)

Pattern matching using case classes is really cool. Let us take an example

 

The above function matches whether the given object is an employee or contractor and takes necessary action. 

More to come in the second part of this tutorial.

References

http://docs.scala-lang.org/index.html