About theTutorial Scala is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. Scala has been created by Martin Odersky and he released the first version in 2003. Scala smoothly integrates the features of object-oriented and functional languages. This tutorial explains the basics of Scala in a simple and reader-friendly way.
Audience This tutorial has been prepared for beginners to help them understand the basics of Scala in simple and easy steps. After completing this tutorial, you will find yourself at a moderate level of expertise in using Scala from where you can take yourself to next levels.
A Scala function declaration has the following form −
def functionName ([list of parameters]) : [return type]
Methods are implicitly declared abstract if you don’t use the equals sign and the method body.
Function Definitions
A Scala function definition has the following form −
Syntax
def functionName ([list of parameters]) : [return type] = {
function body
return [expr]
}
Here, return type could be any valid Scala data type and list of parameters will be a list of variables separated by comma and list of parameters and return type are optional. Very similar to Java, a return statement can be used along with an expression in case function returns a value. Following is the function which will add two integers and return their sum −
Syntax
object add {
def addInt( a:Int, b:Int ) : Int = {
var sum:Int = 0
sum = a + b
return sum
}
}
A function, that does not return anything can return a Unit that is equivalent to void in Java and indicates that function does not return anything. The functions which do not return anything in Scala, they are called procedures.
Syntax
Here is the syntax −
object Hello{
def printMe( ) : Unit = {
println("Hello, Scala!")
}
}
Calling Functions
Scala provides a number of syntactic variations for invoking methods. Following is the standard way to call a method −
functionName( list of parameters )
If a function is being called using an instance of the object, then we would use dot notation similar to Java as follows −
[instance.]functionName( list of parameters )
Try the following example program to define and then call the same function.
Example
object Demo {
def main(args: Array[String]) {
println( "Returned Value : " + addInt(5,7) );
}
def addInt( a:Int, b:Int ) : Int = {
var sum:Int = 0
sum = a + b
return sum
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Variables are nothing but reserved memory locations to store values. This means that when you create a variable, you reserve some space in memory.
Based on the data type of a variable, the compiler allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables.
Variable Declaration
Scala has a different syntax for declaring variables. They can be defined as value, i.e., constant or a variable. Here, myVar is declared using the keyword var. It is a variable that can change value and this is called mutable variable. Following is the syntax to define a variable using var keyword −
Syntax
var myVar : String = "Foo"
Here, myVal is declared using the keyword val. This means that it is a variable that cannot be changed and this is called immutable variable. Following is the syntax to define a variable using val keyword −
Syntax
val myVal : String = "Foo"
Variable Data Types
The type of a variable is specified after the variable name and before equals sign. You can define any type of Scala variable by mentioning its data type as follows −
Syntax
val or val VariableName : DataType = [Initial Value]
If you do not assign any initial value to a variable, then it is valid as follows −
Syntax
var myVar :Int;
val myVal :String;
Variable Type Inference
When you assign an initial value to a variable, the Scala compiler can figure out the type of the variable based on the value assigned to it. This is called variable type inference. Therefore, you could write these variable declarations like this −
Syntax
var myVar = 10;
val myVal = "Hello, Scala!";
Here, by default, myVar will be Int type and myVal will become String type variable.
Multiple assignments
Scala supports multiple assignments. If a code block or method returns a Tuple (Tuple − Holds collection of Objects of different types), the Tuple can be assigned to a val variable. [Note − We will study Tuples in subsequent chapters.]
Syntax
val (myVar1: Int, myVar2: String) = Pair(40, "Foo")
And the type inference gets it right −
Syntax
val (myVar1, myVar2) = Pair(40, "Foo")
Example Program
The following is an example program that explains the process of variable declaration in Scala. This program declares four variables — two variables are defined with variable declaration and remaining two are without variable declaration.
Example
object Demo {
def main(args: Array[String]) {
var myVar :Int = 10;
val myVal :String = "Hello Scala with datatype declaration.";
var myVar1 = 20;
val myVal1 = "Hello Scala new without datatype declaration.";
println(myVar); println(myVal); println(myVar1);
println(myVal1);
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
\>scalac Demo.scala
\>scala Demo
Output
10
Hello Scala with datatype declaration.
20
Hello Scala without datatype declaration.
Variable Scope
Variables in Scala can have three different scopes depending on the place where they are being used. They can exist as fields, as method parameters and as local variables. Below are the details about each type of scope.
Fields
Fields are variables that belong to an object. The fields are accessible from inside every method in the object. Fields can also be accessible outside the object depending on what access modifiers the field is declared with. Object fields can be both mutable and immutable types and can be defined using either var or val.
Method Parameters
Method parameters are variables, which are used to pass the value inside a method, when the method is called. Method parameters are only accessible from inside the method but the objects passed in may be accessible from the outside, if you have a reference to the object from outside the method. Method parameters are always immutable which are defined by val keyword.
Local Variables
Local variables are variables declared inside a method. Local variables are only accessible from inside the method, but the objects you create may escape the method if you return them from the method. Local variables can be both mutable and immutable types and can be defined using either var or val.
This chapter takes you through how to use classes and objects in Scala programming. A class is a blueprint for objects. Once you define a class, you can create objects from the class blueprint with the keyword new. Through the object you can use all functionalities of the defined class.
The following diagram demonstrates the class and object by taking an example of class student, which contains the member variables nameandrollnonameandrollno and member methods setName(setName( and setRollNo). Finally all are members of the class. Class is a blue print and objects are real here. In the following diagram, Student is a class and Harini, John, and Maria are the objects of Student class, those are having name and roll-number.
Scala Classes and Objects
Basic Class
Following is a simple syntax to define a basic class in Scala. This class defines two variables x and y and a method: move, which does not return a value. Class variables are called, fields of the class and methods are called class methods.
The class name works as a class constructor which can take a number of parameters. The above code defines two constructor arguments, xc and yc; they are both visible in the whole body of the class.
Syntax
class Point(xc: Int, yc: Int) {
var x: Int = xc
var y: Int = yc
def move(dx: Int, dy: Int) {
x = x + dx
y = y + dy
println ("Point x location : " + x);
println ("Point y location : " + y);
}
}
As mentioned earlier in this chapter, you can create objects using a keyword new and then you can access class fields and methods as shown below in the example −
Example
import java.io._
class Point(val xc: Int, val yc: Int) {
var x: Int = xc
var y: Int = yc
def move(dx: Int, dy: Int) {
x = x + dx
y = y + dy
println ("Point x location : " + x);
println ("Point y location : " + y);
}
}
object Demo {
def main(args: Array[String]) {
val pt = new Point(10, 20);
// Move to a new location
pt.move(10, 10);
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
\>scalac Demo.scala
\>scala Demo
Output
Point x location : 20
Point y location : 30
Extending a Class
You can extend a base Scala class and you can design an inherited class in the same way you do it in Java (use extends key word), but there are two restrictions: method overriding requires the override keyword, and only the primary constructor can pass parameters to the base constructor. Let us extend our above class and add one more class method.
Example
Let us take an example of two classes Point class assameexampleasaboveassameexampleasabove and Location class is inherited class using extends keyword. Such an ‘extends’ clause has two effects: it makes Location class inherit all non-private members from Point class, and it makes the type Location a subtype of the type Point class. So here the Point class is called superclass and the class Location is called subclass. Extending a class and inheriting all the features of a parent class is called inheritance but Scala allows the inheritance from just one class only.
Note − Methods move method in Point class and move method in Location class do not override the corresponding definitions of move since they are different definitions forexample,theformertaketwoargumentswhilethelattertakethreeargumentsforexample,theformertaketwoargumentswhilethelattertakethreearguments.
Try the following example program to implement inheritance.
import java.io._
class Point(val xc: Int, val yc: Int) {
var x: Int = xc
var y: Int = yc
def move(dx: Int, dy: Int) {
x = x + dx
y = y + dy
println ("Point x location : " + x);
println ("Point y location : " + y);
}
}
class Location(override val xc: Int, override val yc: Int,
val zc :Int) extends Point(xc, yc){
var z: Int = zc
def move(dx: Int, dy: Int, dz: Int) {
x = x + dx
y = y + dy
z = z + dz
println ("Point x location : " + x);
println ("Point y location : " + y);
println ("Point z location : " + z);
}
}
object Demo {
def main(args: Array[String]) {
val loc = new Location(10, 20, 15);
// Move to a new location
loc.move(10, 10, 5);
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
\>scalac Demo.scala
\>scala Demo
Output
Point x location : 20
Point y location : 30
Point z location : 20
Implicit Classes
Implicit classes allow implicit conversations with class’s primary constructor when the class is in scope. Implicit class is a class marked with ‘implicit’ keyword. This feature is introduced in Scala 2.10.
Syntax − The following is the syntax for implicit classes. Here implicit class is always in the object scope where all method definitions are allowed because implicit class cannot be a top level class.
Syntax
object <object name> {
implicit class <class name>(<Variable>: Data type) {
def <method>(): Unit =
}
}
Example
Let us take an example of an implicit class named IntTimes with the method times. It means the times contain a loop transaction that will execute the given statement in number of times that we give. Let us assume the given statement is “4 times println “Hello”“Hello”” means the println “”Hello”“”Hello” statement will execute 4 times.
The following is the program for the given example. In this example two object classes are used RunandDemoRunandDemo so that we have to save those two classes in different files with their respective names as follows.
Run.scala − Save the following program in Run.scala.
object Run {
implicit class IntTimes(x: Int) {
def times [A](f: =>A): Unit = {
def loop(current: Int): Unit =
if(current > 0){
f
loop(current - 1)
}
loop(x)
}
}
}
Demo.scala − Save the following program in Demo.scala.
import Run._
object Demo {
def main(args: Array[String]) {
4 times println("hello")
}
}
The following commands are used to compile and execute these two programs.
Command
\>scalac Run.scala
\>scalac Demo.scala
\>scala Demo
Output
Hello
Hello
Hello
Hello
Note −
Implicit classes must be defined inside another class/object/trait notintoplevelnotintoplevel.
Implicit classes may only take one non –implicit argument in their constructor.
Implicit classes may not be any method, member or object in scope with the same name as the implicit class.
Singleton Objects
Scala is more object-oriented than Java because in Scala, we cannot have static members. Instead, Scala has singleton objects. A singleton is a class that can have only one instance, i.e., Object. You create singleton using the keyword object instead of class keyword. Since you can't instantiate a singleton object, you can't pass parameters to the primary constructor. You already have seen all the examples using singleton objects where you called Scala's main method.
Following is the same example program to implement singleton.
Example
import java.io._
class Point(val xc: Int, val yc: Int) {
var x: Int = xc
var y: Int = yc
def move(dx: Int, dy: Int) {
x = x + dx
y = y + dy
}
}
object Demo {
def main(args: Array[String]) {
val point = new Point(10, 20)
printPoint
def printPoint{
println ("Point x location : " + point.x);
println ("Point y location : " + point.y);
}
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.