Free Shipping

Secure Payment

easy returns

24/7 support

  • Home
  • Blog
  • Scala Tutorial Part 3 – Introduction to Classes and Objects in Scala

Scala Tutorial Part 3 – Introduction to Classes and Objects in Scala

 July 15  | 0 Comments

In our previous blog, we have discussed Control structures and the Functions in Scala. In this blog, we will be discussing the Classes and Objects in Scala. As you are aware, Scala supports both Functional as well as Object oriented features. Let’s begin with object oriented features of Scala i.e., Class, Inheritance, Abstract Class, Objects, Case Classes and finally, Traits.

Class

Scala classes are similar to Java classes. The classic definition of a class is as follows: A class is nothing but a blueprint or a template for creating different objects which defines its properties and behaviours. We can use the same class syntax which we use in Java for Scala also, but it is not a Scala style of class. Scala has its own style of defining classes.

Syntax

Class ClassName(Parameters) {
//body
}

Scala is something special; a Scala class accepts parameters as well. These parameters are optional and we may or may not pass them depending on our requirement, but the class definition is mandatory.

  • A var parameter will create a field, getter and setter.

  • A val parameter will create a field and getter.

The members of a class in Scala are public by default.

Now let’s create a class and an object for that class in the Scala shell.

Here, we have defined a class with name demo and have created an object called ‘mydemo’ as shown in the above screen shot. After the creation of object, we have tried to check the type of the created object with :t mydemo and we have got the output as demo which says that the object acquires the properties of the class demo.

The constructor for a class Scala is inbuilt and the parameters for the class are the arguments for the constructor in Scala.

Now, let’s create a Scala class for cars which accepts car_model, car_speed and car_price as parameters.

In the above screen shot, you can see that a Scala class with name PartialScalaCar has been created and it accepts the parameters car_model, car_speed and car_price, and just like in Java, we have defined the getters and setters for the price to set our own price to the car. Then we have created a main object so that we can create as many car objects we want with the Part  features.

We have created two objects here car1, car2 with the features of PartialScalaCar class and then we have added them in a list and we are iterating on the list to print them.

We can modify this class again as shown in the below screen shot.

The difference between both the types is that in the above scenario, we have passed the parameters to the class and inside the class we have declared them. But here, we have declared the parameters at the time of passing them.

Scala provides getters and setters automatically to the members of the class. If it is val scala, it will give only the getter since they are immutable. And if the member is var, it gives both getters and setters, since var is mutable.

Access Modifiers

Like in any other programming languages, Scala also has 3 types of access modifiers. They are as follows:

  • Private – Visible only inside the class or object.

  • Protected – Only accessible from the sub class.

  • Public – Accessed from anywhere (Default).

Object

Objects are the instances of the class, but in Scala these are more than the instances. In Scala, we can create a new object with the below syntax:

Object ObjectName {
body
}

The syntax looks similar to class without parameters. A new instance for the class is created with the help of keyword new.

In our previous post, we have seen about the functions in Scala. Those functions can also be referred as objects in Scala.

Inheritance

Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. With the use of inheritance, the information is made manageable in a hierarchical order. The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class).

Like in Java, we can obtain the inheritance in Scala by using the keyword extendsYou can refer to the below screen shot to know how a class can be inherited.

In the above screen shot, you can see that we have overridden the method printCarInfo to print the latest info of the cars which is in the class ScalaCar.

Abstract Class

A class that is declared with abstract keyword, is known as abstract class. Abstraction is a process of hiding the implementation details and showing only the functionality to the user.

In other words, it shows only important things to the user and hides the internal details. For example, when sending SMS, you just type the text and send the message. You don’t know the internal processing about the message delivery.

The syntax for creating Abstract classes in Scala is shown below:

Abstract class className(parameters){
body
}

Singletons

Singleton is the mechanism to limit the creation of number of objects to one. We use the singleton classes mostly when creating access to databases, where we need only one person to access the database and also when we don’t want any duplications.

A singleton object is declared using the object keyword.

Companion Objects

When a singleton object is named the same as a class, it is called a companion object. A companion object must be defined inside the same source file as the class. You can refer to the below screen shot to know how we have implemented Companion Objects.

 

Case Classes

Case classes generates lots of useful boiler plate code. In computer programming, boilerplate code or boilerplate is the sections of code that have to be included in many places with little or no alteration.

Syntax:

case calss ClassName(parameters){
body
}

Case classes automatically generates the following:

  • Getter methods for the constructor arguments.

  • Hashcode and equals.

  • Copy method.

  • Companion object with apply/unapply.

  • toString.

Case classes are primarily intended to create “immutable records�? that you can easily use in pattern-matching expressions.

Note: These are only some of the functions of Case classes.

Traits

Traits are similar to interfaces in Java. Additionally it contains concrete members, meaning, it can contain both implemented and unimplemented methods, assigned and un-assigned fields.

Syntax:

trait TraitName{
body
}

Similar to Java interfaces, traits cannot be instantiated directly as they may contain unimplemented methods so we need to implement the traits with any concrete class first before instantiating them.

A class can extend only one class, but it can extend any number of traits and a Trait can only extend other Traits. If a class implements one trait it will use the extends keyword. And if a class implements multiple traits, it will extend the first trait (or a class, or abstract class), and then use WITH keyword for other traits.

 

In the above screen shot, we have declared a trait SpeedCar and we have extended this trait with the concrete class ScalaCar. Aand then, there is a unimplemented method in the trait moveBack() which needs to be implemented in the concrete class. So, we have implemented this moveBack() in the ScalaCar class.

Hope this post was helpful in understanding the classes and objects in Scala. In case of any queries, feel free to write to us at support@acadgild.com.

In our next blog on Scala series, we will be discussing about Pattern Matching, Exception Handling, Option[T], Closure, File Operations, Lazy vals.

Register to our free Scala course to learn more about it. Keep visiting our site www.acadgild.com for more updates on Bigdata and other technologies. Click here to learn Bigdata Hadoop from our Expert Mentors

>