0% found this document useful (0 votes)
5 views27 pages

Scala Unit 2

Uploaded by

mehthegoat4510
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views27 pages

Scala Unit 2

Uploaded by

mehthegoat4510
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

191AIC302T-Object Oriented Programming with SCALA

Unit-II
Scala OOPS Concepts - Objects and Class

Object and Class - Singleton object - Companion Objects - Case classes and objects –
Constructors – Method overloading and overriding – Field overriding - Extending a class –
implicit classes – inner classes – Traits - Pattern Matching – Extractors -Collection Classes

2.1 Object and Class

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:

1) State: data values of an object are known as its state.

2) Behavior: functionality that an object performs is known as its behavior.

Object in scala is an instance of class. It is also known as runtime entity.

Class

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.

Department of AI & DSPage 1


191AIC302T-Object Oriented Programming with SCALA
Unit-II

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

Scala Sample Example2 of Class

In scala, you can create class like this also. Here, constructor is created in class definition. This is
called primary constructor.

class Student(id:Int, name:String){ // Primary constructor


def show(){
println(id+" "+name)
}
}
object MainObject{
def main(args:Array[String]){
var s = new Student(100,"Martin") // Passing values to constructor
s.show() // Calling a function by using an object
}
}
Output:
100 Martin

Department of AI & DSPage 2


191AIC302T-Object Oriented Programming with SCALA
Unit-II

Scala Example of class that maintains the records of students

class Student(id:Int, name:String){


def getRecord(){
println(id+" "+name);
}
}
object MainObject{
def main(args: Array[String]){
var student1 = new Student(101,"Raju");
var student2 = new Student(102,"Martin");
student1.getRecord();
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.

Scala Anonymous object Example

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

2.2 Singleton object and Companion Objects

Singleton Object

 Singleton object is an object which is declared by using object keyword instead by class.
No object is required to call methods declared inside singleton object.

Department of AI & DSPage 3


191AIC302T-Object Oriented Programming with SCALA
Unit-II

 In scala, there is no static concept. So scala creates a singleton object to provide entry
point for your program execution.
 If you don't create singleton object, your code will compile successfully but will not
produce any output. Methods declared inside Singleton Object are accessible globally. A
singleton object can extend classes and traits.

Scala Singleton Object Example

object Singleton{

def main(args:Array[String]){

SingletonObject.hello() // No need to create object.

object SingletonObject{

def hello(){

println("Hello, This is Singleton Object")

Scala Companion Object

 In scala, when you have a class with same name as singleton object, it is called
companion class and the singleton object is called companion object.
 The companion class and its companion object both must be defined in the same source
file.

Scala Companion Object Example

class ComapanionClass{

def hello(){

println("Hello, this is Companion Class.")

Department of AI & DSPage 4


191AIC302T-Object Oriented Programming with SCALA
Unit-II
object CompanoinObject{

def main(args:Array[String]){

new ComapanionClass().hello()

println("And this is Companion Object.")

2.3 Case classes and objects

A Scala Case Class is like a regular class, except it is good for modeling immutable data. It also
serves useful in pattern matching, such a class has a default apply() method which handles object
construction. A scala case class also has all vals, which means they are immutable.

Creating a Case Class

The creation of case class is simple, the keyword case class is used to define it followed by its
name and a set of parameters that can be empty.

Syntax:

case class cc_Name (paramter(s))

Code snippet to create a case class in Scala

case class student(name: String, class: Int, marks: Int, result: String)

Case Objects

The case objects are nothing but the instances of case class in Scala.

Creating case objects

obj_name = cc_name(parameter_values)

Could you see and understood, there is no new keyword used in the definition of case object
which is because it uses the apply() method.

Example

case class student(name: String, standard: Int, marks: Int, result: String )

object myObject {

def main(args: Array[String]) {

Department of AI & DSPage 5


191AIC302T-Object Oriented Programming with SCALA
Unit-II
// Creating a case Object

val student1 = student("Prem", 10, 89, "A+")

println("Case Object: " + student1)

Operations on the case class

Comparing Case Objects

In Scala, case objects can be compared using == expression which returns true or false based on
the comparison.

Syntax:

case_Obj1 == case_Obj2

Example

case class student(name: String, standard: Int, marks: Int, result: String )

object myObject {

def main(args: Array[String]) {

// Creating a case Object

val student1 = student("Prem", 10, 89, "A+")

println("Case Object student1 : " + student1)

val student2 = student("Ramesh", 11, 56, "B")

println("Case Object student2 : " + student2)

val student3 = student("Prem", 10, 89, "A+")

println("Case Object student3 : " + student3)

val comp1 = student1 == student2

println("Comparison of student1 and student2 = " + comp1)

val comp2 = student1 == student3

Department of AI & DSPage 6


191AIC302T-Object Oriented Programming with SCALA
Unit-II
println("Comparison of student1 and student3 = " + comp2)

Coping Case Class in Scala

 We can copy the contents of one case object to another fully and partially too.
 Copying case object using copy() method [shallow copy]:
 The copy() method on the case object is used to copy the contents of one object to another. This is
a shallow copy.
Syntax:
caseObj1 = caseObj2.copy()

Example

case class student(name: String, standard: Int, marks: Int, result: String )
object myObject {
def main(args: Array[String]) {
// Creating a case Object
val student1 = student("Prem", 10, 89, "A+")
println("Case Object student1 : " + student1)

val copyObj = student1.copy()


println("Copied Object: " + copyObj)
}
}

2.4 Constructors
A constructor is a function that is called at the time of initialization of objects. A constructor is
just like a method of a class that contains instructions to be executed. The constructor has the
same name as the class and is called when the object of the class is initialized.

Default Primary Constructor


 In scala, if you don't specify primary constructor, compiler creates a constructor which is
known as primary constructor.
 All the statements of class body treated as part of constructor. It is also known as default
constructor.
Example:
class Student{
println("Hello from default constructor");
}
Department of AI & DSPage 7
191AIC302T-Object Oriented Programming with SCALA
Unit-II
Scala programming language defines two types of constructors,
 Primary constructor
 Auxiliary constructor

1) Primary constructor
Also known as default constructor, a primary constructor is created when no other constructor is
defined. It has the same name as the class. It is defined by default in Scala.

Syntax:

class class_name(parameter list){


// statements to be executed...
}
Example:

class student(Sname: String, Ssubject: String, percentage: Int)


{
def result()
{
println("Student name: " + Sname);
println("Subject taken: " + Ssubject);
println("Percentage obtained:" + percentage);
}
}
object MyObject
{
def main(args: Array[String])
{
var obj = new student("Ramesh", "Maths", 78);
obj.result();
}
}
2) Auxiliary constructor
In a Scala class, programmers are allowed to create multiple constructors for a single class. But
there can be only one primary constructor of a class. Constructor that is explicitly defined by the
programmer other than the primary is known as an auxiliary constructor.
Syntax:

def this(parameter list){


//code to be executed

Department of AI & DSPage 8


191AIC302T-Object Oriented Programming with SCALA
Unit-II
}
There can be multiple auxiliary constructors which can be differentiated by their parameter list. In
the definition of any auxiliary constructor, the first statement should be a call to the primary
constructor or another auxiliary constructor which is defined before the calling constructor using
"this" keyword.

Example:
class Student( Sname: String, sub: String)
{
var percentage: Float = 0.0f;
def display()
{
println("Student name: " + Sname);
println("Stream : " + sub);
println("percentage: " + percentage);

}
def this(Sname: String, sub: String, no:Int)
{
this(Sname, sub)
this.percentage = no/5
}
}
object Main
{
def main(args: Array[String])
{
var obj = new Student("kirti", "biology", 345);
obj.display();
}
}

Constructor Overloading
 In scala, you can overload constructor. Let's see an example.
class Student(id:Int){
def this(id:Int, name:String)={
this(id)
println(id+" "+name)
}
println(id)

Department of AI & DSPage 9


191AIC302T-Object Oriented Programming with SCALA
Unit-II
}

object MainObject{
def main(args:Array[String]){
new Student(101)
new Student(100,"India")
}
}

2.5 Method overloading and overriding


 Method overloading is a method that is redefined in different ways under the same name.
 Method overloading is one of the methods used to implement polymorphism in Scala.

Implementation of method overloading in Scala

To create an overloaded method in Scala, define multiple methods with the same name and
different parameter list and return type. This means defining multiple functions one with one
parameter of type ‘A’ other with two parameters, etc.

Syntax:

//Method 1 :
def fun (a : data_type ) {
// code to be executed
}

//Method 2 :
def fun(a : data_type , b : data_type ){
// code to be executed
}
Both these methods contribute to method overloading in Scala. Now, to create an overloaded
method can invert either of the following things in the function that lead to overloading the
method:

Methods with different parameter lists


Methods with different data types and order
Program to show implementation of method overloading in Scala | print area of different figures
using method overloading

object MyClass {

Department of AI & DSPage 10


191AIC302T-Object Oriented Programming with SCALA
Unit-II
def peri(x:Int, y:Int){
println("The perimeter of rectangle is "+ (x+y))
}
def peri(a:Int , b:Int ,c:Int){
println("The perimeter of rectangle is "+ (a+b+c))
}
def peri(r:Int){
println("The perimeter of rectangle is "+ (2*(3.14)*r))
}
def main(args: Array[String]) {
println("Program to print perimeter of different figures using method overloading: ")
println("Perimeter of rectangle: ")
peri(12 , 345)
println("Perimeter of triangle: ")
peri(3, 5, 8)
println("Perimeter of circle:")
peri(4)
}
}

Program to show implementation of method overloading in Scala | print data-type of the


parameter using method overloading

object MyClass {
def datatype(x:Int){
println("The parameter is of Integer datatype")
}
def datatype(x:Float){
println("The parameter is of Float data type")
}
def datatype(x:Char){
println("The parameter is of Character data type")
}
def datatype(x: Boolean){
println("The parameter is of Boolean data type")
}
def main(args: Array[String]) {
println("Program to print data type using method overloading: ")
datatype(4)
datatype(4.0f)

Department of AI & DSPage 11


191AIC302T-Object Oriented Programming with SCALA
Unit-II
datatype('f')
datatype(true)
}
}
Method Overriding
 When a subclass has the same name method as defined in the parent class, it is known as
method overriding. When subclass wants to provide a specific implementation for the
method defined in the parent class, it overrides method from parent class.
 In scala, you must use either override keyword or override annotation to override methods
from parent class.

Scala Method Overriding Example


class Vehicle{
def run(){
println("vehicle is running")
}
}
class Bike extends Vehicle{
override def run(){
println("Bike is running")
}
}
object MainObject{
def main(args:Array[String]){
var b = new Bike()
b.run()
}
}
Output:
Bike is running

2.6 Field overriding

Overriding is the concept in which the child class is allowed to redefine the members of the parent
class. Both methods and variables/ fields can be overridden in object-oriented programming. In
Scala as well both methods and Fields can be overridden but overriding of fields has some
restrictions on implementation.

Overriding fields in Scala

Department of AI & DSPage 12


191AIC302T-Object Oriented Programming with SCALA
Unit-II
 For overriding fields in Scala, some rules must be kept in mind to avoid errors that arise
while implementing this concept,
 The use of override keyword is necessary to implement the concept field overriding. If
you missed the keyword an error will be prompted and execution of the code will be
stopped.
 Only fields that are defined using the val keyboard for defining fields in both parent class
and child class can be overridden.
 Fields that are defined using the var keyword cannot be overridden as they are editable (
that is both read and write operations are allowed on the variable) anywhere in the class.
Here are some programs that show the implementation of field overriding and Scala.

This program will show what will be the output if override keyword is not used?

class animal{
val voice = "animal's voice"
}
class dog extends animal{
val voice = "Dog bark's...!"
def says(){
println(voice)
}
}
class cat extends animal{
val voice = "cat meow's...!";
def says(){
println(voice)
}
}
object MainObject{
def main(args:Array[String]){
var ani = new dog()
ani.says()
}
}
Output

error: overriding value voice in class animal of type String;


value voice needs `override' modifier
val voice = "Dog bark's...!"
^

Department of AI & DSPage 13


191AIC302T-Object Oriented Programming with SCALA
Unit-II
error: overriding value voice in class animal of type String;
value voice needs `override' modifier
val voice = "cat meow's...!";
^
two errors found

This program will show what will be the output if override keyword is used?

class animal{
val voice = "animal's voice"
}
class dog extends animal{
override val voice = "Dog bark's...!"
def says(){
println(voice)
}
}
class cat extends animal{
override val voice = "Cat meow's...!";
def says(){
println(voice)
}
}
object MainObject{
def main(args:Array[String]){
var ani = new dog()
ani.says()
var ani2 = new cat()
ani2.says()
}
}
Output
Dog bark's...!
Cat meow's...!
3) Python program with var keyword

This program will show what will be the output if var keyword is used?

class animal{
var voice = "animal's voice"

Department of AI & DSPage 14


191AIC302T-Object Oriented Programming with SCALA
Unit-II
}
class dog extends animal{
override var voice = "Dog bark's...!"
def says(){
println(voice)
}
}
class cat extends animal{
override var voice = "Cat meow's...!";
def says(){
println(voice)
}
}
object MainObject{
def main(args:Array[String]){
var ani = new dog()
ani.says()
var ani2 = new cat()
ani2.says()
}
}
Output
error: overriding variable voice in class animal of type String;
variable voice cannot override a mutable variable
override var voice = "Dog bark's...!"
^
error: overriding variable voice in class animal of type String;
variable voice cannot override a mutable variable
override var voice = "Cat meow's...!";
^
two errors found

2.7 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

Department of AI & DSPage 15


191AIC302T-Object Oriented Programming with SCALA
Unit-II
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).

class Point(val xc: Int, val yc: Int) {


var x: Int = xc
var y: Int = yc

def move(dx: Int, dy: Int) {


x = x + dx
y = y + dy
println ("Point x location : " + x);
println ("Point y location : " + y);
}
}
class Location(override val xc: Int, override val yc: Int,
val zc :Int) extends Point(xc, yc){
var z: Int = zc
def move(dx: Int, dy: Int, dz: Int) {
x = x + dx
y = y + dy
z = z + dz
println ("Point x location : " + x);
println ("Point y location : " + y);
println ("Point z location : " + z);
}
}

object Demo {
def main(args: Array[String]) {
val loc = new Location(10, 20, 15);

// Move to a new location

Department of AI & DSPage 16


191AIC302T-Object Oriented Programming with SCALA
Unit-II
loc.move(10, 10, 5);
}
}

2.8 Implicit Classes


 Implicit classes allow implicit conversations with class’s primary constructor when the
class is in scope. Implicit class is a class marked with ‘implicit’ keyword. This feature is
introduced in Scala 2.10.

Syntax − The following is the syntax for implicit classes. Here implicit class is always in the
object scope where all method definitions are allowed because implicit class cannot be a top level
class.

Syntax
object <object name> {
implicit class <class name>(<Variable>: Data type) {
def <method>(): Unit =
}
}
Example
Let us take an example of an implicit class named IntTimes with the method times(). It means the
times () contain a loop transaction that will execute the given statement in number of times that
we give. Let us assume the given statement is “4 times println (“Hello”)” 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.

Run.scala − Save the following program in Run.scala.

object Run {
implicit class IntTimes(x: Int) {
def times [A](f: =>A): Unit = {
def loop(current: Int): Unit =

if(current > 0){


f
loop(current - 1)
}

Department of AI & DSPage 17


191AIC302T-Object Oriented Programming with SCALA
Unit-II
loop(x)
}
}
}
Demo.scala − Save the following program in Demo.scala.

import Run._

object Demo {
def main(args: Array[String]) {
4 times println("hello")
}
}
The following commands are used to compile and execute these two programs.
Command
\>scalac Run.scala
\>scalac Demo.scala
\>scala Demo
Output
Hello
Hello
Hello
Hello

2.9 Inner Classes

Inner Class is a special concept in Scala using which we can create a class inside another class.
It is used for grouping together classes to improve the usability of the concept of encapsulation in
Scala.

Though Scala inherits many features from Java but, the binding of inner classes. The inner class
in Scala is bound to outer object.

In Scala, they can be different types of inner class definitions,

1. Creating a class inside another class


2. Creating a class inside an object
3. Creating an object inside a class

Department of AI & DSPage 18


191AIC302T-Object Oriented Programming with SCALA
Unit-II
1) Creating a class inside another class
We can define a class inside another class. Accessing the inner class member will require creating
the object of inner class using the object of outer class.

Syntax:
class outerClass{
class innerClass{
// members of innerClass
}
}
Program:
Illustrating the working of the inner class, creating a class inside another class,
// Illustrating the working of inner class

class outerClass{
class innerClass{
def printVal() {
println("This is inner Class from Outer Class!")
}
}
}
object myObjects {
def main(args: Array[String]) {
val outObj = new outerClass()
val inObj = new outObj.innerClass
inObj.printVal
}
}
Output:
This is inner Class from Outer Class!

2) Creating a class inside an object


We can define a class inside an Object. And accessing class needs object for creation.

Syntax:
new outerObject.innerClass().member
Program:

// Illustrating the working of inner class,


// Creating inner class inside outer Object...

Department of AI & DSPage 19


191AIC302T-Object Oriented Programming with SCALA
Unit-II

object OuterObject{
class innerClass{
def printVal() {
println("This is inner Class from Outer Object!")
}
}
}

object myObjects {
def main(args: Array[String]) {
val inObj = new OuterObject.innerClass()
inObj.printVal
}
}
Output:
This is inner Class from Outer Object!

3) Creating an object inside a class


We can define an Object inside a class in Scala. And accessing object needs to create object of the
outerClass.

Syntax:

new outerClass().innerObject.member
Program:

// Illustrating the working of inner class,


// Creating inner object inside outer class...
class outerClass{
object innerObject{
def printVal() {
println("This is inner Object from Outer Class!")
}
}
}

object myObjects {
def main(args: Array[String]) {
val inObj = new outerClass().innerObject

Department of AI & DSPage 20


191AIC302T-Object Oriented Programming with SCALA
Unit-II
inObj.printVal
}
}
Output:
This is inner Object from Outer Class!

2.10 Traits
 Traits in Scala are like interfaces in Java. A trait can have fields and methods as members,
these members can be abstract and non-abstract while creation of trait.

The implementation of Scala traits can implement a trait in a Scala Class or Object.
Some features of Scala traits:
 Members can be abstract as well as concrete members.
 A trait can be extended by another trait.
 Made using "trait" keyword.

Syntax:
trait trait_name{
def method()
}

Example showing the use of trait


trait Iterator[A] {
def hasNext: Boolean
def next(): A
}
class IntIterator(to: Int) extends Iterator[Int] {
private var current = 0
override def hasNext: Boolean = current < to
override def next(): Int = {
if (hasNext) {
val t = current
current += 1
t
} else 0
}
}
val iterator = new IntIterator(10)
iterator.next() // returns 0
iterator.next() // returns 1

Department of AI & DSPage 21


191AIC302T-Object Oriented Programming with SCALA
Unit-II
This example shows the use of trait and how it is inherited? The code creates a trait name Iterator,
this trait there are 2 abstract methods hasNext and next. Both the methods are defined in the class
IntInterator which defines the logic. And then creates objects for this class to use the trait
function.

Another working example,


trait hello{
def greeting();
}
class Ihelp extends hello {
def greeting() {
println("Hello! This is include Help! ");
}
}

object MyClass {
def main(args: Array[String]) {
var v1 = new Ihelp();
v1.greeting
}
}
Output
Hello! This is include Help!
This code prints "Hello! This is include Help!" using trait function redefinition and then calling
that function.

Some pros and cons about using traits


 Traits are a new concept in Scala so they have limited usage and less interoperability. So,
for a Scala code That can be used with a Java code should not use traits. The abstract class
would be a better option.
 Traits can be used when the feature is to be used in multiple classes, you can use traits
with other classes too.
 If a member is to be used only once then the concrete class should be used rather than a
Traits it improves the efficiency of the code and makes it more reliable.

2.11 Pattern Matching

Scala pattern matching: pattern matching feature is check for the equivalence of an object with a
string. In Scala pattern matching classes are strong.

Department of AI & DSPage 22


191AIC302T-Object Oriented Programming with SCALA
Unit-II
Matching a pattern contains a sequence of alternative of the pattern to be considered. Each
sequence is a case of the Scala pattern matching. For all alternatives, the case has expressions
which are evaluated for matching pattern matches. The arrow symbol '=>' is used as a separator
between the patterns and expressions.

The match keyword is used to define a pattern matching block. This block contain cases that are
that turns that if matched will execute a set of expressions (a block of code).

In Pattern matching, there must be at least one case (also called alternative) with sum values for
which the input pattern can be matched. If no keyword is matched then the last catch-all(_) case
is executed. The expression that is evaluated after the matches found is actually a block code that
is needed to be Evaluated. For a pattern-matching function, any sort of data can be matched
based on first match policy (for you cases matching, the first one is used).

Example:

object Demo {

def matchno(x: Int): String = x match {

case 1 => "Hello"

case 2 => "Welcome"

case _ => "to Scala "

def main(args: Array[String]) {

println(matchno(3))

Matching using Case Classes

The case classes are special classes that are used in pattern matching with case expressions.
Syntactically, these are standard classes with a special modifier: case.

Try the following, it is a simple pattern matching example using case class.

Example

object Demo {

Department of AI & DSPage 23


191AIC302T-Object Oriented Programming with SCALA
Unit-II
def main(args: Array[String]) {

val alice = new Person("Alice", 25)

val bob = new Person("Bob", 32)

val charlie = new Person("Charlie", 32)

for (person <- List(alice, bob, charlie)) {

person match {

case Person("Alice", 25) => println("Hi Alice!")

case Person("Bob", 32) => println("Hi Bob!")

case Person(name, age) => println(

"Age: " + age + " year, name: " + name + "?")

case class Person(name: String, age: Int)

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.
 Second, the compiler automatically implements equals, hashCode, and toString methods
to the class, which use the fields specified as constructor arguments. So, we no longer
need our own toString() methods.
 Finally, also, the body of Person class becomes empty because there are no methods that
we need to define!

2.12 Extractors

An extractor is a special type of object that has some special methods. These methods are:
apply() and unapply().

Department of AI & DSPage 24


191AIC302T-Object Oriented Programming with SCALA
Unit-II

 The apply() method of extractor object is used to feeding values for the object, it takes
parameter values, formats them and adds them to the object.
 The unapply() method of extractor object is used to delete values from the object, it
matches the value and removes them from the object list.

Working of extractors

Let's take an example of an object that apply() as well as unapply() method. The apply() method
takes arguments and adds them to class. The unapply() does the exact opposite, it takes
arguments, matches them and then deletes, i.e. deconstructs.

Program:

object Student
{
def main(args: Array[String])
{
def apply(name: String, result: String) =
{
name +" is "+ result
}

def unapply(x: String): Option[(String, String)] =


{
val y = x.split("is")
if (y.length == 2 && y(1)=="Pass")
{
Some(y(0), y(1))

}
else
None
}
println ("The Apply method returns : " +
apply("Ram", "Pass"))
println ("The Unapply method returns : " +
unapply("RamisPass"))
}
}

Department of AI & DSPage 25


191AIC302T-Object Oriented Programming with SCALA
Unit-II
2.13 Collection Classes

 A collection in programming is a simple object used to collect data. It groups together


elements into a single entity (object). You can do the operation is to add, delete, update
data using collections.
 In Scala, there is a huge base of collection libraries. There is a wide hierarchy of
collections in Scala. Basic collections contain linear sets.
 The collection in Scala can be mutable as well as immutable.

A mutable collection is a collection whose elements can be updated and elements are added or
removed from it. It allows all these operations.

An immutable collection does not allow the user to do the update operation or add and remove
operation on it. There is an option to do this, but on every operation, a new collection is created
with updated value and the old one is discarded.

Based on how they have used the collections are classified as lazy or strict. If created as a lazy
collection, it may not consume memory space until they are called by the program.

As the hierarchy is concerned, we have a list of collections, with Traversable trait, it allows
you to traverse the collection i.e. visit each element in the collection one by one. Traversable
has followed another trait Iterable that allows iterating over the elements of the collection.

Here we are listing some commonly used collections that you will encounter in your Scala
programming life. There is a huge base that supports them, this is just an overview;

Scala List

The list is a linear array-like collection. It stores a similar type of elements and uses a linked
list type storage method. List is an immutable collection that extends linearSeq trait.

Scala Tuple

Tuple in Scala is an immutable collection. It can contain a fixed number of elements of


different types i.e. it can hold an integer and string together.

Scala Set

A set is a type collection that contains elements of the same data type, it does not contain any
duplicate elements. Set can mutable as well as immutable in Scala.

Scala Map

A map is a collection that contains key-value pairs. To retrieve the value the key is used.

Department of AI & DSPage 26


191AIC302T-Object Oriented Programming with SCALA
Unit-II

Department of AI & DSPage 27

You might also like