Scala

26 / 53

Scala - Classes and Objects




Not able to play video? Try with vimeo

What is a class? A class is a way of creating your own data type. A class is a way of representing a type of value inside the system. For example, we can create a data type that represents a customers using a class. A customer would have states like first name, last name, age, address and contact number. A customer class might represent behaviors for how these states can be transformed for example how to change a customer's address or name. These behaviors are called methods. A class is not concrete until it has been instantiated using a “new” keyword.

Let's define a class. Login to the CloudxLab web console and type scala. As you can see on the screen, we've defined a person class and it has three parameters - first name of string type, last name of string type and age of integer type.

We've assigned these parameters to immutable class variables. Let's create an instance of the class. Type val obj = new Person("Robin", "Gill", 42); ..we've created an instance of Person class with firstname as Robin, lastname as Gill and age as 42.

We can access class variables from the instance. Type obj.firstname to get the firstname of the person and obj.age to get the age of the person.

Let's define a class method to get the full name of the person.

As you can see on the screen, we have defined a method getFullName. This method concatenates firstname and lastname and returns a full name which is of string type.

Let's create an instance of the class and call the getFullName method. We can see that the full name of the person "Robin Gill" is printed on the screen.

Objects in Scala are Singleton. A singleton is a class which can only have one instance at any point in time.

Methods and values that aren’t associated with individual instances of a class belong in singleton objects.

A singleton class can be directly accessed via its name. We can create a singleton class using the keyword object.

Let's create an object Hello which has a method message which returns a string "hello". We can access the method message without instantiating the instance of "Hello". This is because Hello is a singleton object and it is already instantiated for us when we try to call the message method. Type Hello.message to access the message method

Objects are useful in defining constants and utility methods as they are not related to any specific instance of the class. Utility methods take parameters and return values based on a calculation and transformation


Loading comments...