Learn Scala
Learn Scala
Scala - Home
Scala - Overview
Scala - Environment Setup
Scala - Basic Syntax
Scala - Data Types
Scala - Variables
Scala - Classes & Objects
Scala - Access Modifiers
Scala - Operators
Scala - IF ELSE
Scala - Loop Statements
Scala - Functions
Scala - Closures
Scala - Strings
Scala - Arrays
Scala - Collections
Scala - Traits
Scala - Pattern Matching
Scala - Regular Expressions
Scala - Exception Handling
Scala - Extractors
Scala - Files I/O
Selected Reading
UPSC IAS Exams Notes
Developer's Best Practices
Questions and Answers
Effective Resume Writing
HR Interview Questions
Computer Glossary
Who is Who
Advertisements
Previous Page
Next Page
Scala - Overview
Scala, short for Scalable Language, is a hybrid functional programming language. It was
created by Martin Odersky. 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.
Here we have presented a few points that makes Scala the first choice of application
developers.
Scala is object-oriented
Scala is a pure object-oriented language in the sense that every value is an object. Types
and behavior of objects are described by classes and traits which will be explained in
subsequent chapters.
Classes are extended by subclassing and a flexible mixin-based composition
mechanism as a clean replacement for multiple inheritance.
Scala is functional
Scala is also a functional language in the sense that every function is a value and every
value is an object so ultimately every function is an object.
The Scala compiler compiles your Scala code into Java Byte Code, which can then be
executed by the 'scala' command. The 'scala' command is similar to the java
command, in that it executes your compiled Scala code.
Scala vs Java
Scala has a set of features that completely differ from Java. Some of these are −
Nested Functions
Traits
Closures
If the Java installation has been done properly, then it will display the current version
and specification of your Java installation. A sample output is given in the following table.
We assume that the readers of this tutorial have Java SDK version 1.8.0_31 installed on
their system.
In case you do not have Java SDK, download its current version from
http://www.oracle.com/technetwork/java/javase/downloads/index.html and install it.
Windows
1
Set JAVA_HOME to C:\ProgramFiles\java\jdk1.7.0_60
Linux
2
Export JAVA_HOME=/usr/local/java-current
Append the full path of Java compiler location to the System Path.
Windows
1
Append the String "C:\Program Files\Java\jdk1.7.0_60\bin" to the end of the system
variable PATH.
2 Linux
Export PATH=$PATH:$JAVA_HOME/bin/
Execute the command java -version from the command prompt as explained above.
Command −
Output −
1................................................
[ Starting to unpack ]
Finally, open a new command prompt and type Scala -version and press Enter. You
should see the following −
Fields − Each object has its unique set of instance variables, which are called
fields. An object's state is created by the values assigned to these fields.
Interactive Mode
Open the command prompt and use the following command to open Scala.
\>scala
Type the following text to the right of the Scala prompt and press the Enter key −
Hello, Scala!
Script Mode
Use the following instructions to write a Scala program in script mode. Open notepad
and add the following code into it.
Example
object HelloWorld {
*/
}
}
Open the command prompt window and go to the directory where the program file is
saved. The ‘scalac’ command is used to compile the Scala program and it will generate
a few class files in the current directory. One of them will be called HelloWorld.class.
This is a bytecode which will run on Java Virtual Machine (JVM) using ‘scala’ command.
Use the following command to compile and execute your Scala program.
Output
Hello, World!
Basic Syntax
The following are the basic syntaxes and coding conventions in Scala programming.
Class Names − For all class names, the first letter should be in Upper Case. If
several words are used to form a name of the class, each inner word's first letter
should be in Upper Case.
Method Names − All method names should start with a Lower Case letter. If
multiple words are used to form the name of the method, then each inner word's
first letter should be in Upper Case.
Program File Name − Name of the program file should exactly match the object
name. When saving the file you should save it using the object name (Remember
Scala is case-sensitive) and append ‘.scala’ to the end of the name. (If the file
name and the object name do not match your program will not compile).
Example − Assume 'HelloWorld' is the object name. Then the file should be saved
as 'HelloWorld.scala'.
def main(args: Array[String]) − Scala program processing starts from the
main() method which is a mandatory part of every Scala Program.
Scala Identifiers
All Scala components require names. Names used for objects, classes, variables and
methods are called identifiers. A keyword cannot be used as an identifier and identifiers
are case-sensitive. Scala supports four types of identifiers.
Alphanumeric Identifiers
An alphanumeric identifier starts with a letter or an underscore, which can be followed
by further letters, digits, or underscores. The '$' character is a reserved keyword in Scala
and should not be used in identifiers.
Operator Identifiers
An operator identifier consists of one or more operator characters. Operator characters
are printable ASCII characters such as +, :, ?, ~ or #.
The Scala compiler will internally "mangle" operator identifiers to turn them into legal
Java identifiers with embedded $ characters. For instance, the identifier :-> would be
represented internally as $colon$minus$greater.
Mixed Identifiers
A mixed identifier consists of an alphanumeric identifier, which is followed by an
underscore and an operator identifier.
unary_+, myvar_=
Here, unary_+ used as a method name defines a unary + operator and myvar_= used
as method name defines an assignment operator (operator overloading).
Literal Identifiers
A literal identifier is an arbitrary string enclosed in back ticks (` . . . `).
Scala Keywords
The following list shows the reserved words in Scala. These reserved words may not be
used as constant or variable or any other identifier names.
- : = =>
# @
Comments in Scala
Scala supports single-line and multi-line comments very similar to Java. Multi-line
comments may be nested, but are required to be properly nested. All characters
available inside any comment are ignored by Scala compiler.
object HelloWorld {
*/
println("Hello, world!")
Newline Characters
Scala is a line-oriented language where statements may be terminated by semicolons
(;) or newlines. A semicolon at the end of a statement is usually optional. You can type
one if you want but you don't have to if the statement appears by itself on a single line.
On the other hand, a semicolon is required if you write multiple statements on a single
line. Below syntax is the usage of multiple statements.
Scala Packages
A package is a named module of code. For example, the Lift utility package is
net.liftweb.util. The package declaration is the first non-comment line in the source file
as follows −
package com.liftcode.stuff
Scala packages can be imported so that they can be referenced in the current
compilation scope. The following statement imports the contents of the scala.xml
package −
import scala.xml._
You can import a single class and object, for example, HashMap from the
scala.collection.mutable package −
import scala.collection.mutable.HashMap
You can import more than one class or object from a single package, for example,
TreeMap and TreeSet from the scala.collection.immutable package −
Apply Dynamic
A marker trait that enables dynamic invocations. Instances x of this trait allow method
invocations x.meth(args) for arbitrary method names meth and argument lists args as
well as field accesses x.field for arbitrary field namesfield. This feature is introduced in
Scala-2.10.
If a call is not natively supported by x (i.e. if type checking fails), it is rewritten according
to the following rules −
Byte
1
8 bit signed value. Range from -128 to 127
Short
2
16 bit signed value. Range -32768 to 32767
Int
3
32 bit signed value. Range -2147483648 to 2147483647
Long
4
64 bit signed value. -9223372036854775808 to 9223372036854775807
Float
5
32 bit IEEE 754 single-precision float
Double
6
64 bit IEEE 754 double-precision float
Char
7
16 bit unsigned Unicode character. Range from U+0000 to U+FFFF
String
8
A sequence of Chars
Boolean
9
Either the literal true or the literal false
Unit
10
Corresponds to no value
11 Null
null or empty reference
Nothing
12
The subtype of every other type; includes no values
Any
13
The supertype of any type; any object is of type Any
AnyRef
14
The supertype of any reference type
All the data types listed above are objects. There are no primitive types like in Java. This
means that you can call methods on an Int, Long, etc.
Integral Literals
Integer literals are usually of type Int, or of type Long when followed by a L or l suffix.
Here are some integer literals −
0
035
21
0xFFFFFFFF
0777L
0.0
1e30f
3.14159f
1.0e100
.1
Boolean Literals
The Boolean literals true and false are members of type Boolean.
Symbol Literals
A symbol literal 'x is a shorthand for the expression scala.Symbol("x"). Symbol is a
case class, which is defined as follows.
package scala
final case class Symbol private (name: String) {
override def toString: String = "'" + name
}
Character Literals
A character literal is a single character enclosed in quotes. The character is either a
printable Unicode character or is described by an escape sequence. Here are some
character literals −
'a'
'\u0041'
'\n'
'\t'
String Literals
A string literal is a sequence of characters in double quotes. The characters are either
printable Unicode character or are described by escape sequences. Here are some string
literals −
"Hello,\nWorld!"
"This string contains a \" character."
Multi-Line Strings
A multi-line string literal is a sequence of characters enclosed in triple quotes """ ... """.
The sequence of characters is arbitrary, except that it may contain three or more
consecutive quote characters only at the very end.
Characters must not necessarily be printable; newlines or other control characters are
also permitted. Here is a multi-line string literal −
Null Values
The null value is of type scala.Null and is thus compatible with every reference type. It
denotes a reference value which refers to a special "null" object.
Escape Sequences
The following escape sequences are recognized in character and string literals.
\b \u0008 backspace BS
\n \u000c formfeed FF
\f \u000c formfeed FF
\\ \u005c backslash \
A character with Unicode between 0 and 255 may also be represented by an octal
escape, i.e., a backslash '\' followed by a sequence of up to three octal characters.
Following is the example to show few escape sequence characters −
Example
object Test {
println("Hello\tWorld\n\n" );
When the above code is compiled and executed, it produces the following result −
Output
Hello World
Scala - Variables
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"
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;
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")
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 type
declaration and remaining two are without type declaration.
Example
object Demo {
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.
The following diagram demonstrates the class and object by taking an example of class
student, which contains the member variables (name and roll no) and member methods
(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.
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
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._
var x: Int = xc
var y: Int = yc
x = x + dx
y = y + dy
}
object Demo {
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 (as same example as above) 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
(for example, the former take two arguments while the latter take three arguments).
import java.io._
var x: Int = xc
var y: Int = yc
x = x + dx
y = y + dy
var z: Int = zc
x = x + dx
y = y + dy
z = z + dz
println ("Point x location : " + x);
object Demo {
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
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”)” means the println (“”Hello”) statement will execute 4 times.
The following is the program for the given example. In this example two object classes
are used (Run and Demo) so that we have to save those two classes in different files
with their respective names as follows.
object Run {
loop(current - 1)
loop(x)
}
import Run._
object Demo {
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 (not in top level).
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.
Example
import java.io._
var x: Int = xc
var y: Int = yc
x = x + dx
y = y + dy
object Demo {
printPoint
def printPoint{
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 : 10
Point y location : 20
Private Members
A private member is visible only inside the class or object that contains the member
definition.
Example
class Outer {
class Inner {
class InnerMost {
f() // OK
In Scala, the access (new Inner). f() is illegal because f is declared private in Inner and
the access is not from within class Inner. By contrast, the first access to f in class
Innermost is OK, because that access is contained in the body of class Inner. Java would
permit both accesses because it lets an outer class access private members of its inner
classes.
Protected Members
A protected member is only accessible from subclasses of the class in which the member
is defined.
Example
package p {
class Super {
f()
class Other {
}
The access to f in class Sub is OK because f is declared protected in ‘Super’ class and
‘Sub’ class is a subclass of Super. By contrast the access to f in ‘Other’ class is not
permitted, because class ‘Other’ does not inherit from class ‘Super’. In Java, the latter
access would be still permitted because ‘Other’ class is in the same package as ‘Sub’
class.
Public Members
Unlike private and protected members, it is not required to specify Public keyword for
Public members. There is no explicit modifier for public members. Such members can
be accessed from anywhere.
Example
class Outer {
class Inner {
class InnerMost {
f() // OK
Scope of Protection
Access modifiers in Scala can be augmented with qualifiers. A modifier of the form
private[X] or protected[X] means that access is private or protected "up to" X, where X
designates some enclosing package, class or singleton object.
Example
package society {
package professional {
class Executive {
println(another.workDetails)
println(another.secrets) //ERROR
Variable workDetails will be accessible to any class within the enclosing package
professional.
Variable friends will be accessible to any class within the enclosing package
society.
Variable secrets will be accessible only on the implicit object within instance
methods (this).
Scala - Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. Scala is rich in built-in operators and provides the following types of
operators −
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
This chapter will examine the arithmetic, relational, logical, bitwise, assignment and
other operators one by one.
Arithmetic Operators
The following arithmetic operators are supported by Scala language. For example, let us
assume variable A holds 10 and variable B holds 20, then −
Show Examples
Relational Operators
The following relational operators are supported by Scala language. For example let us
assume variable A holds 10 and variable B holds 20, then −
Show Examples
Logical Operators
The following logical operators are supported by Scala language. For example, assume
variable A holds 1 and variable B holds 0, then −
Show Examples
Bitwise Operators
Bitwise operator works on bits and perform bit by bit operation. The truth tables for &,
|, and ^ are as follows −
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by Scala language is listed in the following table.
Assume variable A holds 60 and variable B holds 13, then −
Show Examples
Assignment Operators
There are following assignment operators supported by Scala language −
Show Examples
Simple assignment operator, Assigns values from C = A + B will assign value of A + B into
=
right side operands to left side operand C
Take a look at the following table. Operators with the highest precedence appear at the
top of the table and those with the lowest precedence appear at the bottom. Within an
expression, higher precedence operators will be evaluated first.
Flow Chart
The following is a flow chart diagram for conditional statement.
if Statement
‘if’ statement consists of a Boolean expression followed by one or more statements.
Syntax
The syntax of an ‘if’ statement is as follows.
if(Boolean_expression) {
// Statements will execute if the Boolean expression is true
}
If the Boolean expression evaluates to true then the block of code inside the ‘if’
expression will be executed. If not, the first set of code after the end of the ‘if’ expression
(after the closing curly brace) will be executed.
Try the following example program to understand conditional expressions (if expression)
in Scala Programming Language.
Example
object Demo {
var x = 10;
if( x < 20 ){
println("This is if statement");
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
This is if statement
If-else Statement
An ‘if’ statement can be followed by an optional else statement, which executes when
the Boolean expression is false.
Syntax
The syntax of a if...else is −
if(Boolean_expression){
//Executes when the Boolean expression is true
} else{
//Executes when the Boolean expression is false
}
Try the following example program to understand conditional statements (if- else
statement) in Scala Programming Language.
Example
object Demo {
var x = 30;
if( x < 20 ){
println("This is if statement");
} else {
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
This is else statement
If-else-if-else Statement
An 'if' statement can be followed by an optional 'else if...else' statement, which is very
useful to test various conditions using single if...else if statement.
When using if , else if , else statements there are few points to keep in mind.
An 'if' can have zero or one else's and it must come after any else if's.
An 'if' can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of he remaining else if's or else's will be tested.
Syntax
The following is the syntax of an ‘if...else if...else’ is as follows −
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
} else if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
} else if(Boolean_expression 3){
//Executes when the Boolean expression 3 is true
} else {
//Executes when the none of the above condition is true.
}
Try the following example program to understand conditional statements (if- else- if-
else statement) in Scala Programming Language.
Example
object Demo {
var x = 30;
if( x == 10 ){
println("Value of X is 10");
} else if( x == 20 ){
println("Value of X is 20");
} else if( x == 30 ){
println("Value of X is 30");
} else{
}
}
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
Value of X is 30
Syntax
The syntax for a nested if-else is as follows −
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}
}
Example
object Demo {
var x = 30;
var y = 10;
if( x == 30 ){
if( y == 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
X = 30 and Y = 10
There may be a situation, when you need to execute a block of code several number of
times. In general, statements are executed sequentially: The first statement in a
function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more
complicated execution paths.
Flow Chart
Scala programming language provides the following types of loops to handle looping
requirements. Click the following links in the table to check their detail.
while loop
1
Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.
do-while loop
2
Like a while statement, except that it tests the condition at the end of the loop body.
for loop
3 Executes a sequence of statements multiple times and abbreviates the code that manages
the loop variable.
break statement
1
Terminates the loop statement and transfers execution to the statement immediately
following the loop.
Example
object Demo {
var a = 10;
// An infinite loop.
while( true ){
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
If you will execute above code, it will go in infinite loop which you can terminate by
pressing Ctrl + C keys.
Value of a: 10
Value of a: 10
Value of a: 10
Value of a: 10
…………….
Scala - Functions
A function is a group of statements that perform a task. You can divide up your code
into separate functions. How you divide up your code among different functions is up to
you, but logically, the division usually is so that each function performs a specific task.
Scala has both functions and methods and we use the terms method and function
interchangeably with a minor difference. A Scala method is a part of a class which has
a name, a signature, optionally some annotations, and some bytecode where as a
function in Scala is a complete object which can be assigned to a variable. In other
words, a function, which is defined as a member of some object, is called a method.
A function definition can appear anywhere in a source file and Scala permits nested
function definitions, that is, function definitions inside other function definitions. Most
important point to note is that Scala function's name can have characters like +, ++, ~,
&,-, --, \, /, :, etc.
Function Declarations
A Scala function declaration has the following form −
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 −
Try the following example program to define and then call the same function.
Example
object Demo {
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.
Command
\>scalac Demo.scala
\>scala Demo
Output
Returned Value : 12
Scala functions are the heart of Scala programming and that's why Scala is assumed as
a functional programming language. Following are few important concepts related to
Scala functions which should be understood by a Scala programmer.
Functions Call-by-Name Functions with Named Arguments
Scala - Closures
A closure is a function, whose return value depends on the value of one or more
variables declared outside this function.
Here the only variable used in the function body, i * 10 , is i, which is defined as a
parameter to the function. Try the following code −
There are two free variables in multiplier: i and factor. One of them, i, is a formal
parameter to the function. Hence, it is bound to a new value each time multiplier is
called. However, factor is not a formal parameter, then what is this? Let us add one
more line of code.
var factor = 3
val multiplier = (i:Int) => i * factor
Now factor has a reference to a variable outside the function but in the enclosing scope.
The function references factor and reads its current value each time. If a function has
no external references, then it is trivially closed over itself. No external context is
required.
Example
object Demo {
def main(args: Array[String]) {
var factor = 3
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
multiplier(1) value = 3
multiplier(2) value = 6
Scala - Strings
This chapter takes you through the Scala Strings. In Scala, as in Java, a string is an
immutable object, that is, an object that cannot be modified. On the other hand, objects
that can be modified, like arrays, are called mutable objects. Strings are very useful
objects, in the rest of this section, we present important methods of java.lang.String
class.
Creating a String
The following code can be used to create a String −
or
Example
object Demo {
println( greeting )
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
Hello, world!
As mentioned earlier, String class is immutable. String object once created cannot be
changed. If there is a necessity to make a lot of modifications to Strings of characters
then use String Builder Class available in Scala!.
String Length
Methods used to obtain information about an object are known as accessor methods.
One accessor method that can be used with strings is the length() method, which returns
the number of characters contained in the string object.
Example
object Demo {
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
String Length is : 17
Concatenating Strings
The String class includes a method for concatenating two strings −
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end. You can also
use the concat() method with string literals, as in −
Which results in −
"Hello, world!"
Example
object Demo {
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
Dot Dot saw I was Tod
Try the following example program, which makes use of printf() method −
Example
object Demo {
println(fs)
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
The value of the float variable is 12.456000,
while the value of the integer variable is 2000,
and the string is Hello, Scala!()
String Interpolation
String Interpolation is the new way to create Strings in Scala programming language.
This feature supports the versions of Scala-2.10 and later. String Interpolation: The
mechanism to embed variable references directly in process string literal.
The following example code snippet for the implementation of ‘s’ interpolator in
appending String variable ($name) to a normal String (Hello) in println statement.
Example
object Demo {
println(s"Hello, $name")
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
Hello, James
1 + 1 = 2
The ‘ f ’ Interpolator
The literal ‘f’ interpolator allows to create a formatted String, similar to printf in C
language. While using ‘f’ interpolator, all variable references should be followed by the
printf style format specifiers such as %d, %i, %f, etc.
Let us take an example of append floating point value (height = 1.9d) and String variable
(name = “James”) with normal string. The following code snippet of implementing ‘f’
Interpolator. Here $name%s to print (String variable) James and $height%2.2f to print
(floating point value) 1.90.
It is type safe (i.e.) the variable reference and following format specifier should match
otherwise it is showing error. The ‘ f ’ interpolator makes use of the String format utilities
(format specifiers) available in Java. By default means, there is no % character after
variable reference. It will assume as %s (String).
‘raw’ Interpolator
The ‘raw’ interpolator is similar to ‘s’ interpolator except that it performs no escaping of
literals within a string. The following code snippets in a table will differ the usage of ‘s’
and ‘raw’ interpolators. In outputs of ‘s’ usage ‘\n’ effects as new line and in output of
‘raw’ usage the ‘\n’ will not effect. It will print the complete string with escape letters.
Program − Program −
} }
} }
Output −
Output −
Result =
a Result = \n a \n b
b
String Methods
Following is the list of methods defined by java.lang.String class and can be used
directly in your Scala programs −
Sr.No Methods with Description
int compareTo(Object o)
2
Compares this String to another Object.
6 Returns true if and only if this String represents the same sequence of characters as the
specified StringBuffer.
12 Encodes this String into a sequence of bytes using the platform's default charset, storing
the result into a new byte array.
13 Encodes this String into a sequence of bytes using the named charset, storing the result
into a new byte array.
int hashCode()
15
Returns a hash code for this string.
17 Returns the index within this string of the first occurrence of the specified character, starting
the search at the specified index.
19 Returns the index within this string of the first occurrence of the specified substring,
starting at the specified index.
String intern()
20
Returns a canonical representation for the string object.
24 Returns the index within this string of the last occurrence of the specified substring,
searching backward starting at the specified index.
int length()
25
Returns the length of this string.
boolean regionMatches(boolean ignoreCase, int toffset, String other, int offset, int
len)
27
Tests if two string regions are equal.
29 Returns a new string resulting from replacing all occurrences of oldChar in this string with
newChar.
30 Replaces each substring of this string that matches the given regular expression with the
given replacement.
31 Replaces the first substring of this string that matches the given regular expression with
the given replacement.
char[] toCharArray()
39
Converts this string to a new character array.
String toLowerCase()
40 Converts all of the characters in this String to lower case using the rules of the default
locale.
String toString()
42
This object (which is already a string!) is itself returned.
String toUpperCase()
43 Converts all of the characters in this String to upper case using the rules of the default
locale.
String toUpperCase(Locale locale)
44
Converts all of the characters in this String to upper case using the rules of the given Locale.
String trim()
45
Returns a copy of the string, with leading and trailing whitespace omitted.
Scala - Arrays
Scala provides a data structure, the array, which stores a fixed-size sequential collection
of elements of the same type. An array is used to store a collection of data, but it is
often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99,
you declare one array variable such as numbers and use numbers[0], numbers[1], and
..., numbers[99] to represent individual variables. This tutorial introduces how to declare
array variables, create arrays, and process arrays using indexed variables. The index of
the first element of an array is the number zero and the index of the last element is the
total number of elements minus one.
Syntax
var z:Array[String] = new Array[String](3)
or
Here, z is declared as an array of Strings that may hold up to three elements. Values
can be assigned to individual elements or get access to individual elements, it can be
done by using commands like the following −
Command
z(0) = "Zara"; z(1) = "Nuha"; z(4/2) = "Ayan"
Here, the last example shows that in general the index can be any expression that yields
a whole number. There is one more way of defining an array −
Following picture represents an array myList. Here, myList holds ten double values and
the indices are from 0 to 9.
Processing Arrays
When processing array elements, we often use loop contol structures because all of the
elements in an array are of the same type and the size of the array is known.
Below is an example program of showing how to create, initialize and process arrays −
Example
object Demo {
total += myList(i);
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
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
Scala does not directly support various array operations and provides various methods
to process arrays in any dimension. If you want to use the different methods then it is
required to import Array._ package.
Multi-Dimensional Arrays
There are many situations where you would need to define and use multi-dimensional
arrays (i.e., arrays whose elements are arrays). For example, matrices and tables are
examples of structures that can be realized as two-dimensional arrays.
This is an array that has three elements each being an array of integers that has three
elements.
Example
import Array._
object Demo {
// build a matrix
for (i <- 0 to 2) {
for ( j <- 0 to 2) {
myMatrix(i)(j) = j;
}
}
for (i <- 0 to 2) {
for ( j <- 0 to 2) {
println();
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
0 1 2
0 1 2
0 1 2
Concatenate Arrays
Try the following example which makes use of concat() method to concatenate two
arrays. You can pass more than one array as arguments to concat() method.
Example
import Array._
object Demo {
println( x )
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
1.9
2.9
3.4
3.5
8.9
7.9
0.4
1.5
Another example: range (10, 20). Here range difference is not given so by default it
assumes 1 element. It create an array with the elements in between 10 and 20 with
range difference 1. Elements in the array are 10, 11, 12, 13, …, and 19.
The following example program shows how to create an array with ranges.
Example
import Array._
object Demo {
println()
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 12 14 16 18
10 11 12 13 14 15 16 17 18 19
def copy( src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int ): Unit
3 Copy one array to another. Equivalent to Java's System.arraycopy(src, srcPos, dest, destPos,
length).
14 Returns an array containing values of a given function over a range of integer values
starting from 0.
def tabulate[T]( n1: Int, n2: Int )( f: (Int, Int ) => T): Array[Array[T]]
Scala - Collections
Scala has a rich set of collection library. Collections are containers of things. Those
containers can be sequenced, linear sets of items like List, Tuple, Option, Map, etc. The
collections may have an arbitrary number of elements or be bounded to zero or one
element (e.g., Option).
Collections may be strict or lazy. Lazy collections have elements that may not consume
memory until they are accessed, like Ranges. Additionally, collections may be mutable
(the contents of the reference can change) or immutable (the thing that a reference
refers to is never changed). Note that immutable collections may contain mutable items.
For some problems, mutable collections work better, and for others, immutable
collections work better. When in doubt, it is better to start with an immutable collection
and change it later if you need mutable ones.
This chapter throws light on the most commonly used collection types and most
frequently used operations over those collections.
Scala Lists
1
Scala's List[T] is a linked list of type T.
Scala Sets
2
A set is a collection of pairwise different elements of the same type.
Scala Maps
3
A Map is a collection of key/value pairs. Any value can be retrieved based on its key.
Scala Tuples
4
Unlike an array or list, a tuple can hold objects with different types.
Scala Options
5
Option[T] provides a container for zero or one element of a given type.
Scala Iterators
6 An iterator is not a collection, but rather a way to access the elements of a collection one
by one.
Scala - Traits
A trait encapsulates method and field definitions, which can then be reused by mixing
them into classes. Unlike class inheritance, in which each class must inherit from just
one superclass, a class can mix in any number of traits.
Traits are used to define object types by specifying the signature of the supported
methods. Scala also allows traits to be partially implemented but traits may not have
constructor parameters.
A trait definition looks just like a class definition except that it uses the keyword trait.
The following is the basic example syntax of trait.
Syntax
trait Equal {
def isEqual(x: Any): Boolean
def isNotEqual(x: Any): Boolean = !isEqual(x)
}
This trait consists of two methods isEqual and isNotEqual. Here, we have not given
any implementation for isEqual where as another method has its implementation. Child
classes extending a trait can give implementation for the un-implemented methods. So
a trait is very similar to what we have abstract classes in Java.
Let us assume an example of trait Equal contain two methods isEqual() and
isNotEqual(). The trait Equal contain one implemented method that is isEqual() so
when user defined class Point extends the trait Equal, implementation to isEqual()
method in Point class should be provided.
Here it is required to know two important method of Scala, which are used in the
following example.
obj.isInstanceOf [Point] To check Type of obj and Point are same are not.
obj.asInstanceOf [Point] means exact casting by taking the object obj type
and returns the same obj as Point type.
Example
trait Equal {
}
class Point(xc: Int, yc: Int) extends Equal {
var x: Int = xc
var y: Int = yc
object Demo {
println(p1.isNotEqual(p2))
println(p1.isNotEqual(p3))
println(p1.isNotEqual(2))
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
true
false
true
Let us take an examples of value classes Weight, Height, Email, Age, etc. For all these
examples it is not required to allocate memory in the application.
A value class not allowed to extend traits. To permit value classes to extend traits,
universal traits are introduced which extends for Any.
Example
object Demo {
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
It will give you the hash code of Wrapper class.
Wrapper@13
If the behavior will not be reused, then make it a concrete class. It is not reusable
behavior after all.
If it might be reused in multiple, unrelated classes, make it a trait. Only traits can
be mixed into different parts of the class hierarchy.
If you plan to distribute it in compiled form, and you expect outside groups to
write classes inheriting from it, you might lean towards using an abstract class.
A pattern match includes a sequence of alternatives, each starting with the keyword
case. Each alternative includes a pattern and one or more expressions, which will be
evaluated if the pattern matches. An arrow symbol => separates the pattern from the
expressions.
Try the following example program, which shows how to match against an integer value.
Example
object Demo {
println(matchTest(3))
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
many
The block with the case statements defines a function, which maps integers to strings.
The match keyword provides a convenient way of applying a function (like the pattern
matching function above) to an object.
Try the following example program, which matches a value against patterns of different
types.
Example
object Demo {
println(matchTest("two"))
println(matchTest("test"))
println(matchTest(1))
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
2
many
one
Try the following, it is a simple pattern matching example using case class.
Example
object Demo {
person match {
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
Hi Alice!
Hi Bob!
Age: 32 year, name: Charlie?
Adding the case keyword causes the compiler to add a number of useful features
automatically. The keyword suggests an association with case expressions in pattern
matching.
First, the compiler automatically converts the constructor arguments into immutable
fields (vals). The val keyword is optional. If you want mutable fields, use the var
keyword. So, our constructor argument lists are now shorter.
Finally, also, the body of Person class becomes empty because there are no methods
that we need to define!
Example
import scala.util.matching.Regex
object Demo {
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
Some(Scala)
We create a String and call the r( ) method on it. Scala implicitly converts the String to
a RichString and invokes that method to get an instance of Regex. To find a first match
of the regular expression, simply call the findFirstIn() method. If instead of finding
only the first occurrence we would like to find all occurrences of the matching word, we
can use the findAllIn( ) method and in case there are multiple Scala words available in
the target string, this will return a collection of all matching words.
You can make use of the mkString( ) method to concatenate the resulting list and you
can use a pipe (|) to search small and capital case of Scala and you can use Regex
constructor instead or r() method to create a pattern.
Try the following example program.
Example
import scala.util.matching.Regex
object Demo {
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
Scala,scala
If you would like to replace matching text, we can use replaceFirstIn( ) to replace the
first match or replaceAllIn( ) to replace all occurrences.
Example
object Demo {
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
Java is scalable and cool
Following is the table listing down all the regular expression Meta character syntax
available in Java.
Subexpression Matches
\\Z Matches end of string. If a newline exists, it matches just before newline.
\\z Matches end of string.
Regular-Expression Examples
Example Description
Note − that every backslash appears twice in the string above. This is because in Java
and Scala a single backslash is an escape character in a string literal, not a regular
character that shows up in the string. So instead of ‘\’, you need to write ‘\\’ to get a
single backslash in the string.
import scala.util.matching.Regex
object Demo {
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
able1
When you want to handle exceptions, you use a try{...}catch{...} block like you would
in Java except that the catch block uses matching to identify and handle the exceptions.
Throwing Exceptions
Throwing an exception looks the same as in Java. You create an exception object and
then you throw it with the throw keyword as follows.
throw new IllegalArgumentException
Catching Exceptions
Scala allows you to try/catch any exception in a single block and then perform pattern
matching against it using case blocks. Try the following example program to handle
exception.
Example
import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException
object Demo {
try {
} catch {
println("IO Exception")
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
Missing file exception
The behavior of this try-catch expression is the same as in other languages with
exceptions. The body is executed, and if it throws an exception, each catch clause is
tried in turn.
Example
import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException
object Demo {
try {
} catch {
println("IO Exception")
}
} finally {
println("Exiting finally...")
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
Missing file exception
Exiting finally...
Scala - Extractors
An extractor in Scala is an object that has a method called unapply as one of its
members. The purpose of that unapply method is to match a value and take it apart.
Often, the extractor object also defines a dual method apply for building values, but
this is not required.
Example
Let us take an example of object defines both apply and unapply methods. The apply
method has the same meaning as always: it turns Test into an object that can be applied
to arguments in parentheses in the same way a method is applied. So you can write
Test ("Zara", "gmail.com") to construct the string "[email protected]".
The unapply method is what turns Test class into an extractor and it reverses the
construction process of apply. Where apply takes two strings and forms an email
address string out of them, unapply takes an email address and returns potentially two
strings: the user and the domain of the address.
The unapply must also handle the case where the given string is not an email address.
That's why unapply returns an Option-type over pairs of strings. Its result is either Some
(user, domain) if the string str is an email address with the given user and domain
parts, or None, if str is not an email address. Here are some examples as follows.
Syntax
unapply("[email protected]") equals Some("Zara", "gmail.com")
unapply("Zara Ali") equals None
Example
object Demo {
if (parts.length == 2){
Some(parts(0), parts(1))
} else {
None
}
}
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
Apply method : [email protected]
Unapply method : Some((Zara,gmail.com))
Unapply method : None
As mentioned above, the purpose of the unapply method is to extract a specific value
we are looking for. It does the opposite operation apply does. When comparing an
extractor object using the match statement the unapply method will be automatically
executed.
Example
object Demo {
val x = Demo(5)
println(x)
x match {
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
10 is bigger two times than 5
Example
import java.io._
object Demo {
writer.write("Hello Scala")
writer.close()
}
Save the above program in Demo.scala. The following commands are used to compile
and execute this program.
Command
\>scalac Demo.scala
\>scala Demo
It will create a file named Demo.txt in the current directory, where the program is
placed. The following is the content of that file.
Output
Hello Scala
Example
object Demo {
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
Please enter your input : Scala is great
Thanks, you just typed: Scala is great
Example
import scala.io.Source
object Demo {
Source.fromFile("Demo.txt" ).foreach {
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
Following is the content read:
Hello Scala