Home » Scala language

Objects in Scala

Objects in Scala: In this tutorial, we are going to learn about the objects in Scala, how to declare an object in Scala? Here, we are also discussing various types of the objects like Lazy initialization of objects, Singleton Object, and Companion object.
Submitted by Shivang Yadav, on June 17, 2019

An object is an instance of the class. It is created in order to use the members of the class i.e. use fields and methods related to the class.

The new keyword is used to create objects of a class.

Syntax:

     var class_name = new obj_name; 

Explanation:

When an object is created all the members are given memory space they require. Variables are created and functions are invoked. The actual call is when the members are called but a space in memory is given to them at the time of object initialization.

Example:

import java.io._

class Student(val rlno: Int, val sname: String, val percent: Int) {
	var rollno: Int = rlno
	var name : String = sname
	var percentage = percent;

	def printresult(){
		print("Roll number : " + rollno);
		print("\nName  : "+ name);
		print("\n Has scored  "+ percentage +" % and is ");
		if(percentage > 40)
			print("passed")
		else 
			print("failed")
	}
}

object Demo {
	def main(args: Array[String]) {
		var stu = new Student(10, "Ramesh", 56);
		stu.printresult();
	}
}

Output

Roll number : 10
Name  : Ramesh
Has scored  56 % and is passed

Lazy initialization of objects

Lazy initialization is done to initialize variables at the time of first access. This increase the efficiency of the code. Lazy variables are defined by lazy modifier.

Syntax:

    lazy var class_name = new obj_name; 

Singleton object

A singleton object is a class that has only one instance. It is a value and is an object defined by the class. It can be reused by defining using import statement and has direct method definition in it.

    Object dog{
        def bark (){
            print("parting")
        }
    } 

Companion object

A companion object has the same name as the class. Both the object and class are each others companion. A companion object can use the private members of the class and add some functionalities to it by its function.

    class circle{
	    def perimeter(var radius){
		    return (2 * 3.14 * radius)
	    }
    }
    object circle {
	    def area( var radius){
		    return (peimeter(radius)*radius)/2;  
	    }
    }

The object uses the class in its function to make a more efficient program. This object can be used using an import package call.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.