Scala Unit 1
Scala Unit 1
1.1 Introduction:
Features of Scala
o Type inference
o Singleton object
o Immutability
o Lazy computation
o Case classes and Pattern matching
o Concurrency control
o String interpolation
o Higher order function
o Traits
o Rich collection set
Type Inference
In Scala, you don't require to mention data type and function return type explicitly. Scala is
enough smart to deduce the type of data. The return type of function is determined by the type of
last expression present in the function.
Singleton object
In Scala, there are no static variables or methods. Scala uses singleton object, which is essentially
class with only one object in the source file. Singleton object is declared by using object instead
of class keyword.
Immutability
Lazy Computation
In Scala, computation is lazy by default. Scala evaluates expressions only when they are
required. You can declare a lazy variable by using lazy keyword. It is used to increase
performance.
Scala case classes are just regular classes which are immutable by default and
decomposable through pattern matching.
All the parameters listed in the case class are public and immutable by default.
Case classes support pattern matching. So, you can write more logical code.
Concurrency control
Scala provides standard library which includes the actor model. You can write
concurrency code by using actor. Scala provides one more platform and tool to deal with
concurrency known as Akka. Akka is a separate open source framework that provides
actor-based concurrency. Akka actors may be distributed or combined with software
transactional memory.
String Interpolation
Since Scala 2.10.0, Scala offers a new mechanism to create strings from your data. It is
called string interpolation. String interpolation allows users to embed variable references
directly in processed string literals. Scala provides three string interpolation methods: s, f
and raw.
Traits
Scala provides rich set of collection library. It contains classes and traits to collect
data. These collections can be mutable or immutable. You can use it according to
your requirement. Scala.collection.mutable package contains all the mutable
collections. You can add, remove and update data while using this package.
Scala.collection.immutable package contains all the immutable collections. It
does not allow you to modify data.
Scala can be installed on any UNIX flavored or Windows based system. Before you start
installing Scala on your machine, you must have Java 1.8 or greater installed on your computer.
Follow the steps given below to install Scala.
Step 1: Verify Your Java Installation
First of all, you need to have Java Software Development Kit (SDK) installed on your system.
To verify this, execute any of the following two commands depending on the platform you are
working on.
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
fromhttp://www.oracle.com/technetwork/java/javase/downloads/index.html and install it.
Step 2: Set Your Java Environment
Set the environment variable JAVA_HOME to point to the base directory location where Java
is installed on your machine. For example,
1 Windows
Set JAVA_HOME to C:\ProgramFiles\java\jdk1.7.0_60
2 Linux
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.
Step 3: Install Scala
You can download Scala from http://www.scala-lang.org/downloads. At the time of writing this
tutorial, I downloaded ‘scala-2.11.5-installer.jar’. Make sure you have admin privilege to
proceed. Now, execute the following command at the command prompt −
Command −
$java –jar scala-2.9.0.1-
installer.jar
Output −
Welcome to the installation of
Scala 2.9.0.1!
The homepage is at During installation, it will ask for license
−http://Scala-lang.org/ agreement, to accept it type 1 and it will
Linux ask a path where Scala will be installed. I
press 1 to continue, 2 to quit, 3
entered /usr/local/share,you can select a
to redisplay
suitable path as per your convenience.
1................................................
[ Starting to unpack ]
[ Processing package: Software
Package Installation (1/1) ]
[ Unpacking finished ]
[ Console installation done ]
Finally, open a new command prompt and type Scala -version and press Enter. You should see
the following −
Basic Syntax:
In a Scala program, it can be defined as a collection of objects that communicate via invoking
each other’s methods. Let us now briefly look into what do class, object, methods and instance
variables mean.
Object − Objects have states and behaviors. An object is an instance of a class. Example
− A dog has states - color, name, breed as well as behaviors - wagging, barking, and
eating.
Class − A class can be defined as a template/blueprint that describes the behaviors/states
that are related to the class.
Methods − A method is basically a behavior. A class can contain many methods. It is in
methods where the logics are written, data is manipulated and all the actions are
executed.
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.
Closure − A closure is a function, whose return value depends on the value of one or
more variables declared outside this function.
Traits − A trait encapsulates method and field definitions, which can then be reused by
mixing them into classes. Traits are used to define object types by specifying the
signature of the supported methods.
First Scala Program
We can execute a Scala program in two modes: one is interactive mode and another isscript
mode.
Interactive Mode
Open the command prompt and use the following command to open Scala.
\>scala
If Scala is installed in your system, the following output will be displayed −
Welcome to Scala version 2.9.0.1
Type in expressions to have them evaluated.
Type :help for more information.
Type the following text to the right of the Scala prompt and press the Enter key −
Example
object HelloWorld {
/* This is my first java program.
* This will print 'Hello World' as the output
*/
def main(args: Array[String]) {
println("Hello, world!") // prints Hello World
}
}
Save the file as − HelloWorld.scala.
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.
\> scalac HelloWorld.scala
\> scala HelloWorld
Output
Hello, World!
Basic Syntax
The following are the basic syntaxes and coding conventions in Scala programming.
Case Sensitivity − Scala is case-sensitive, which means identifier Hello and hellowould
have different meaning in Scala.
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.
Alphanumeric Identifiers
Operator Identifiers
An operator identifier consists of one or more operator characters. Operator characters are
printable ASCII characters such as +, :, ?, ~ or #.
Following are legal operator identifiers −
+ ++ ::: <?> :>
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
Literal Identifiers
- : = =>
# @
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 {
/* This is my first java program.
* This will print 'Hello World' as the output
* This is an example of multi-line comments.
*/
def main(args: Array[String]) {
// Prints Hello World
// This is also an example of single line comment.
println("Hello, world!")
}
}
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
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
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.";
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 byval 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.
Data types:
Scala has all the same data types as Java, with the same memory footprint and precision.
Following is the table giving details about all the data types available in Scala −
1 Byte
8 bit signed value. Range from -128 to 127
2 Short
16 bit signed value. Range -32768 to 32767
3 Int
32 bit signed value. Range -2147483648 to 2147483647
4 Long
64 bit signed value. -9223372036854775808 to 9223372036854775807
5 Float
32 bit IEEE 754 single-precision float
6 Double
64 bit IEEE 754 double-precision float
7 Char
16 bit unsigned Unicode character. Range from U+0000 to U+FFFF
8 String
A sequence of Chars
9 Boolean
Either the literal true or the literal false
10 Unit
Corresponds to no value
11 Null
12 Nothing
The subtype of every other type; includes no values
13 Any
The supertype of any type; any object is of type Any
14 AnyRef
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.
Scala Basic Literals
The rules Scala uses for literals are simple and intuitive. This section explains all basic Scala
Literals.
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
Floating point literals are of type Float when followed by a floating point type suffix F or f, and
are of type Double otherwise. Here are some floating point literals −
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 −
"""the present string
spans three
lines."""
Null Values
Department of AI & DSPage 17
Easwari Engineering College
191AIC302T-Object Oriented Programming with SCALA
Unit-I
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 {
def main(args: Array[String]) {
println("Hello\tWorld\n\n" );
}
}
When the above code is compiled and executed, it produces the following result −
Output
Hello World
1.4 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 –
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 −
> Checks if the value of left operand is greater than (A > B) is not true.
the value of right operand, if yes then condition
becomes true.
< Checks if the value of left operand is less than the (A < B) is true.
value of right operand, if yes then condition
becomes true.
>= Checks if the value of left operand is greater than (A >= B) is not true.
or equal to the value of right operand, if yes then
condition becomes true.
<= Checks if the value of left operand is less than or (A <= B) is true.
equal to the value of right operand, if yes then
condition becomes true.
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 0 0 0 0
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 −
& Binary AND Operator copies a bit to the result if (A & B) will give 12, which is 0000 1100
it exists in both operands.
| Binary OR Operator copies a bit if it exists in (A | B) will give 61, which is 0011 1101
either operand.
^ Binary XOR Operator copies the bit if it is set in (A ^ B) will give 49, which is 0011 0001
one operand but not both.
~ Binary Ones Complement Operator is unary and (~A ) will give -61, which is 1100 0011 in
has the effect of 'flipping' bits. 2's complement form due to a signed
binary number.
<< Binary Left Shift Operator. The bit positions of A << 2 will give 240, which is 1111 0000
the left operands value is moved left by the
number of bits specified by the right operand.
>> Binary Right Shift Operator. The Bit positions of A >> 2 will give 15, which is 1111
the left operand value is moved right by the
number of bits specified by the right operand.
>>> Shift right zero fill operator. The left operands A >>>2 will give 15 which is 0000 1111
value is moved right by the number of bits
Assignment Operators
There are following assignment operators supported by Scala language −
Show Examples
= Simple assignment operator, Assigns values from right C = A + B will assign value of A
side operands to left side operand + B into C
Basic Expressions
val x = 5 + 10 // EXPRESSION
Expressions are evaluated by the compiler to a value, in this case 15. They also have a type, in
this case Int. The type gets figured out by the compiler without us having to specify it. This is
called Type Inference in Scala.
The above expression is mathematical. We could also write another expression that tests for
equality like so:
println(x == 3)
This expression evaluates to a boolean, checking whether or not the value of x is 3, which in this
case is false.
Instructions vs Expressions
Instructions tell the computer to go and do something, for example print to the console or
change the value of a variable. These are used in imperative languages such as Java or
Python
Expressions something that has a value and/or a type. In Scala (and in functional
programming in general) we will start to think in terms of Expressions.
Everything in Scala is an Expression. Only definitions such as val or class or package are
not expressions, everything else is.
What this code is saying for the conditionedValue is “if someCondition is true then the value is
10, otherwise 5”. This is an expression, because it gives back a value.
You could also just write this straight to the console (i.e. without storing it in a val or var) as
below. Both of these lines are expressions in the parentheses that return a value:
println(if(someCondition) 10 else 5)
println(2 + 3)
Create an object called Values and extend it from App, so that we can run it. Type in the
following code:
val x: Int = 99
println(x)
Here we are declaring a VALUE called x, and we are telling the compiler it is of type Int. We
then assign it the value 99. On the next line, we simply print out the value
A key thing to note here, is that once a VAL has been declared, it can’t be reassigned.
val x: Int = 42
println(x)
x = 66
So remember that Vals are immutable. The functional programming style of Scala encourages
the use of these immutable vals.
Type Inference
It isn’t always necessary to include the type when declaring a val. You could instead type:
val x = 42
println(x)
And this would run fine. The type is detected by the compiler by looking at the value assigned to
the variable. This is known as Type Inference.
These are some of the really basic types in Scala, which you should be familiar with from other
programming languages:
val myLong: Long = 35263256234L // notice the L on the end - this tells the compiler its a Long
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.
In scala, a class can contain:
Data member
Member method
Constructor
Block
Nested class
Super class information etc.
You must initialize all instance variables in the class. There is no default scope. If you don't
specify access scope, it is public. There must be an object in which main method is defined. It
provides starting point for your program. Here, we have created an example of class.
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
class Student{
var id:Int = 0; // All fields must be initialized
var name:String = null;
}
object MainObject{
def main(args:Array[String]){
var s = new Student() // Creating an object
println(s.id+" "+s.name);
}
}
Output:
0 null
In scala, you can create class like this also. Here, constructor is created in class definition. This is
called primary constructor.
student2.getRecord();
}
}
Output:
101 Raju
102 Martin
Scala Anonymous object
In scala, you can create anonymous object. An object which has no reference name is called
anonymous object. It is good to create anonymous object when you don't want to reuse it further.
class Arithmetic{
def add(a:Int, b:Int){
var add = a+b;
println("sum = "+add);
}
}
object MainObject{
def main(args:Array[String]){
new Arithmetic().add(10,10);
}
}
Output:
Sum = 20
Object
Object is a real world entity. It contains state and behavior. Laptop, car, cell phone are the real
world objects. Object typically has two characteristics:
Scala provides if statement to test the conditional expressions. It tests boolean conditional
expression which can be either true or false. Scala use various types of if else statements.
If statement
If-else statement
if Statement
‘if’ statement consists of a Boolean expression followed by one or more statements.
Syntax
Example
object Demo {
def main(args: Array[String]) {
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
Example
object Demo {
def main(args: Array[String]) {
var x = 30;
if( x < 20 ){
println("This is if statement");
} else {
println("This is else 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
It is always legal to nest if-else statements, which means you can use one if or else-ifstatement
inside another if or else-if statement.
Syntax
if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}
}
Try the following example program to understand conditional statements (nested- if statement)
in Scala Programming Language.
Example
object Demo {
def main(args: Array[String]) {
var x = 30;
var y = 10;
if( x == 30 ){
if( y == 10 ){
println("X = 30 and 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
The scala if-else-if ladder executes one condition among the multiple conditional statements.
Syntax
if (condition1){
//Code to be executed if condition1 is true
} else if (condition2){
//Code to be executed if condition2 is true
} else if (condition3){
//Code to be executed if condition3 is true
}
...
else {
//Code to be executed if all the conditions are false
}
var number:Int = 85
if(number>=0 && number<50){
println ("fail")
}
else if(number>=50 && number<60){
println("D Grade")
}
else if(number>=60 && number<70){
println("C Grade")
}
else if(number>=70 && number<80){
println("B Grade")
}
else if(number>=80 && number<90){
println("A Grade")
}
else if(number>=90 && number<=100){
println("A+ Grade")
}
else println ("Invalid")
Output:
A Grade
Looping Statements
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.
A loop statement allows us to execute a statement or group of statements multiple times
and following is the general form of a loop statement in most of the programming
languages
Scala programming language provides the following types of loops to handle looping
requirements. Click the following links in the table to check their detail.
1 while loop
Repeats a statement or group of statements while a given condition is true. It tests
the condition before executing the loop body.
2 do-while loop
Like a while statement, except that it tests the condition at the end of the loop
body.
3 for loop
Executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
1 break statement
Terminates the loop statement and transfers execution to the statement
Department of AI & DSPage 35
Easwari Engineering College
191AIC302T-Object Oriented Programming with SCALA
Unit-I
Example
object Demo {
def main(args: Array[String]) {
var a = 10;
// An infinite loop.
while( true ){
println( "Value of a: " + a );
}
}
}
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
object MainObject {
def main(args: Array[String]) {
var a = 10; // Initialization
while( a<=20 ){ // Condition
println(a);
a = a+2 // Incrementation
}
}
}
object MainObject {
def main(args: Array[String]) {
var a = 10; // Initialization
do {
println( a );
a = a + 2; // Increment
}
while( a <= 20 ) // Condition
}
}
for loop
In scala, for loop is known as for-comprehensions. It can be used to iterate, filter and return an
iterated collection. The for-comprehension looks a bit like a for-loop in imperative languages,
except that it constructs a list of the results of all iterations.
Syntax
for( i <- range){
// statements to be executed
}
In the above syntax, range is a value which has start and end point. You can pass range by using
to or until keyword.
The major difference between until and to is, to includes start and end value given in the range,
while until excludes last value of the range. So, the below example will print only 1 to 9.
}
}
You can use for to filter your data. In the below example, we are filtering our data by passing a
conditional expression. This program prints only even values in the given range.
object MainObject {
def main(args: Array[String]) {
for( a <- 1 to 10 if a%2==0 ){
println(a);
}
}
}
In the above example, we have used yield keyword which returns a result after completing of
loop iterations. The for use buffer internally to store iterated result and after finishing all
iterations it yields the final result from that buffer. It does not work like imperative loop.
object MainObject {
def main(args: Array[String]) {
var result = for( a <- 1 to 10) yield a
for(i<-result){
println(i)
}
}
}
In the above example, we have used by keyword. The by keyword is used to skip the iteration.
When you code like: by 2 it means, this loop will skip all even iterations of loop.
object MainObject {
def main(args: Array[String]) {
for(i<-1 to 10 by 2){
println(i)
}
}
}
1.8 Strings
Creating a String
The following code can be used to create a String −
var greeting = "Hello world!";
or
Example
object Demo {
val greeting: String = "Hello, world!"
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.
Use the following code segment to find the length of a string −
Example
object Demo {
def main(args: Array[String]) {
var palindrome = "Dot saw I was Tod";
var len = palindrome.length();
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 −
"My name is ".concat("Zara");
Strings are more commonly concatenated with the + operator, as in −
"Hello," + " world" + "!"
Which results in −
"Hello, world!"
Example
object Demo {
def main(args: Array[String]) {
var str1 = "Dot saw I was ";
var str2 = "Tod";
Command
\>scalac Demo.scala
\>scala Demo
Output
Example
object Demo {
def main(args: Array[String]) {
var floatVar = 12.456
var intVar = 2000
var stringVar = "Hello, Scala!"
var fs = printf("The value of the float variable is " + "%f, while the value of the integer " +
"variable is %d, and the string" + "is %s", floatVar, intVar, stringVar);
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
Example
object Demo {
def main(args: Array[String]) {
val name = "James"
println(s"Hello, $name")
println(s"1 + 1 = ${1 + 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
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.
val height = 1.9d
val name = "James"
println(f"$name%s is $height%2.2f meters tall") //James is 1.90 meters tall
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 −
object Demo { object Demo {
def main(args: Array[String]) { def main(args: Array[String]) {
println(s"Result = \n a \n b") println(raw"Result = \n a \n b")
} }
} }
Output −
Result =
a
b
String Methods
S.No Methods with Description
2 int compareTo(Object o)
Compares this String to another Object.
12 byte getBytes()
Encodes this String into a sequence of bytes using the platform's default charset, storing the
result into a new byte array.
15 int hashCode()
Returns a hash code for this string.
20 String intern()
Returns a canonical representation for the string object.
25 int length()
Returns the length of this string.
27 boolean regionMatches(boolean ignoreCase, int toffset, String other, int offset, int len)
Tests if two string regions are equal.
39 char[] toCharArray()
40 String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the default locale.
42 String toString()
This object (which is already a string!) is itself returned.
43 String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.
45 String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
Example
class StringExample{
var s1 = "Scala string example"
var s2 = "Hello Scala"
var s3 = "Hello Scala"
def show(){
println(s1.equals(s2))
println(s2.equals(s3))
}
}
object MainObject{
def main(args:Array[String]){
var s = new StringExample()
s.show()
}
}
1.9 Arrays
Array is a collection of mutable values. It is an index based data structure which starts
from 0 index to n-1 where n is length of array.
Scala arrays can be generic. It means, you can have an Array[T], where T is a type
parameter or abstract type. Scala arrays are compatible with Scala sequences - you can
pass an Array[T] where a Seq[T] is required. It also supports all the sequence operations.
Following image represents the structure of array where first index is 0, last index is 9 and array
length is 10.
Types of array
Single dimensional array is used to store elements in linear order. Array elements are stored in
contiguous memory space. So, if you have any index of an array, you can easily traverse all the
elements of the array.
class ArrayExample{
var arr = Array(1,2,3,4,5) // Creating single dimensional array
def show(){
for(a<-arr) // Traversing array elements
println(a)
println("Third Element = "+ arr(2)) // Accessing elements by using index
}
}
object MainObject{
def main(args:Array[String]){
var a = new ArrayExample()
a.show()
}
}
Output:
1
2
3
4
5
Third Element = 3
In this example, we have created an array by using new keyword which is used to initialize
memory for array. The entire array elements are set to default value, you can assign that later in
your code.
class ArrayExample{
var arr = new Array[Int](5) // Creating single dimensional array
def show(){
for(a<-arr){ // Traversing array elements
println(a)
}
println("Third Element before assignment = "+ arr(2)) // Accessing elements by using
index
arr(2) = 10 // Assigning new element at 2 index
println("Third Element after assignment = "+ arr(2))
}
}
object MainObject{
def main(args:Array[String]){
var a = new ArrayExample()
a.show()
}
}
Output:
0
0
0
0
Third Element before assignment = 0
Third Element after assignment = 10
Scala Passing Array into Function
You can pass array as an argument to function during function call. Following example illustrate
the process how we can pass an array to the function.
class ArrayExample{
def show(arr:Array[Int]){
for(a<-arr) // Traversing array elements
println(a)
println("Third Element = "+ arr(2)) // Accessing elements by using index
}
}
object MainObject{
def main(args:Array[String]){
var arr = Array(1,2,3,4,5,6) // creating single dimensional array
var a = new ArrayExample()
a.show(arr) // passing array as an argument in the function
}
}
Output:
1
2
3
4
5
6
Third Element = 3
You can also iterate array elements by using foreach loop. Let's see an example.
class ArrayExample{
var arr = Array(1,2,3,4,5) // Creating single dimensional array
arr.foreach((element:Int)=>println(element)) // Iterating by using foreach loop
}
object MainObject{
def main(args:Array[String]){
new ArrayExample()
}
}
Output:
1
2
3
4
5
Multidimensional Array
Multidimensional array is an array which store data in matrix form. You can create from two
dimensional to three, four and many more dimensional array according to your need. Below we
have mentioned array syntax. Scala provides an ofDim method to create multidimensional array.
class ArrayExample{
var arr = Array.ofDim[Int](2,2) // Creating multidimensional array
arr(1)(0) = 15 // Assigning value
def show(){
for(i<- 0 to 1){ // Traversing elements by using loop
for(j<- 0 to 1){
print(" "+arr(i)(j))
}
println()
}
println("Third Element = "+ arr(1)(1)) // Accessing elements by using index
}
}
object MainObject{
def main(args:Array[String]){
var a = new ArrayExample()
a.show()
}
}
Output:
00
15 0
Third Element = 0
Apart from ofDim you can also create multidimensional array by using array of array. In this
example, we have created multidimensional array by using array of array.
class ArrayExample{
var arr = Array(Array(1,2,3,4,5), Array(6,7,8,9,10)) // Creating multidimensional array
def show(){
for(i<- 0 to 1){ // Traversing elements using loop
for(j<- 0 to 4){
print(" "+arr(i)(j))
}
println()
}
}
}
object MainObject{
def main(args:Array[String]){
var a = new ArrayExample()
a.show()
}
}
Output:
12345
6 7 8 9 10
You can manipulate array elements in scala. Here, we are adding two array elements and storing
result into third array.
class ArrayExample{
var arr1 = Array(Array(1,2,3,4,5), Array(6,7,8,9,10)) // Creating multidimensional array
var arr2 = Array(Array(1,2,3,4,5), Array(6,7,8,9,10))
var arr3 = Array.ofDim[Int](2,5)
def show(){
for(i<- 0 to 1){ // Traversing elements using loop
for(j<- 0 to 4){
arr3(i)(j) = arr1(i)(j)+arr2(i)(j)
print(" "+arr3(i)(j))
}
println()
}
}
}
object MainObject{
def main(args:Array[String]){
var a = new ArrayExample()
a.show()
}
}
Output:
2 4 6 8 10
12 14 16 18 20
1.10 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 −
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
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
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.
Command
\>scalac Demo.scala
\>scala Demo
Output
Returned Value : 12
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]
In scala, functions can be composed from other functions. It is a process of composing in which
a function represents the application of two composed functions.
object MainObject {
def main(args: Array[String]) = {
var result = multiplyBy2(add2(10)) // Function composition
println(result)
}
def add2(a:Int):Int = {
a+2
}
def multiplyBy2(a:Int):Int = {
a*2
}
}
Output:
24
Anonymous function is a function that has no name but works as a function. It is good to create
an anonymous function when you don't want to reuse it latter.
You can create anonymous function either by using => (rocket) or _ (underscore) wild card in
scala.
object MainObject {
def main(args: Array[String]) = {
var result1 = (a:Int, b:Int) => a+b // Anonymous function by using => (rocket)
var result2 = (_:Int)+(_:Int) // Anonymous function by using _ (underscore) wild card
println(result1(10,10))
println(result2(10,10))
}
}
Output:
20
20
Expressions those are written in multiple lines are called multiline expression. In scala, be
carefull while using multiline expressions.
The following program explains about if we break an expression into multiline, the scala
compiler throw a warning message.
Output:
10
You can apply following ways to avoid above problem.
object MainObject {
def add2(a:Int, b:Int) = {
a+
b
}
def add3(a:Int, b:Int) = {
(a
+b)
}
def main(args: Array[String]) = {
var result2 = add2(10,10)
var result3 = add3(10,10)
println(result2+"\n"+result3)
}
}
Output:
20
20
In scala, method may have multiple parameter lists. When a method is called with a
fewer number of parameter lists, then this will yield a function taking the missing
parameter lists as its arguments.
In other words it is a technique of transforming a function that takes multiple arguments
into a function that takes a single argument.
object MainObject {
def add(a:Int)(b:Int) = {
a+b
}
def main(args: Array[String]) = {
var result = add(10)(10)
println("10 + 10 = "+result)
var addIt = add(10)_
var result2 = addIt(3)
println("10 + 3 = "+result2)
}
}
Output:
20
1.10.7 Closures
A closure is a function, whose return value depends on the value of one or more variables
declared outside this function.
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]) {
println( "multiplier(1) value = " + multiplier(1) )
println( "multiplier(2) value = " + multiplier(2) )
}
var factor = 3
val multiplier = (i:Int) => i * factor
}