×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Scala Object and Class Object

By IncludeHelp Last updated : October 22, 2024

Scala Class Object

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.

Creating Class Object

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: Int = percent  // Explicit type for percentage

  // Method to print result
  def printResult(): Unit = {
    println(s"Roll number: $rollno")
    println(s"Name: $name")
    print(s"Has scored $percentage% and is ")
    if (percentage > 40)
      println("passed")
    else
      println("failed")
  }
}

object Demo {
  def main(args: Array[String]): Unit = {
    val 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.

Example

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.

Example

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.