Scala class and Object- How Object work in Scala with Examples

Updated:03/09/2023 by Computer Hope

Unlike java and other oops languages, scala is a pure object oriented programming language. It allows us to create object and class as follow rules of OOPS Concept so that you can develop object oriented applications.

Object is a real world entity. It contains state and attribute as well behavior or nature of entity. Laptop, car, cell phone are the real world objects. Object typically has two characteristics:

To conclude, Object is blue print of Class . We are going to implement this class in below example.

Below is example of object Keyword "MainObject" which is invoke main method .

We are created Student class and class members.
we define object and invoke main method.
An object in Scala is a special construct that represents a singleton instance of a class.
It is created using the object keyword in our code "MainObject".


                                 
 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);      
     
                   } 
                     
     
                } 

Creation of Scala class

As mentioned previously, a class provides the blueprints for objects. So basically, an object is created from a class.
In Scala, the constructor is used to create new objects.

  • Declaration − A variable declaration with a variable name with an object type.
  • Instantiation : initialise using constructor.
  • Execution of class Object

                             
     class Person(name: String, age: Int, salary : Int) {
        // Fields
        private val fullName: String = s"Mr/Ms. $name"
      
        // Method
        def myGreet(): Unit = {
          println(s"Hello, my name is $fullName, and I am $age years old.")
        }
      }
      object PersonApp {
        def main(args: Array[String]): Unit = {
          val person = new Person("Alice", 30)
          person.myGreet()
        }
      }
      
                           
                        

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.

    To define an implicit class, you must follow these rules:
  • The class must be defined within an object or a package object.
  • The constructor of the implicit class must take exactly one parameter.
  • The implicit class must have the implicit keyword before its definition.

                         
     object Implicits {
        implicit class StringEnhancer(original: String) {
          def exclamationify(): String = s"$original!"
          def repeat(n: Int): String = original * n
        }
      }
      
      object DevloperIndiaDemo {
        import Implicits._
      
        def main(args: Array[String]): Unit = {
          val message = "Hello, this is developer Indian "
          val exclamationMyMessage = message.exclamationify()
          println(exclamationMyMessage) // Output: "Hello, this is developer Indian"
      
          val repeatedMyMessage = message.repeat(2)
          println(repeatedMyMessage) // Output: "Hello, this is developer Indian Hello, this is developer Indian "
        }
      }
                       
                    

Companion objects

Scala also supports the concept of companion objects.
A companion object is an object specified in the same file with the same name as a class. The class and the companion object can both access each other's private members. It is frequently used to specify factory methods, retain shared state, and define class-related methods.

                        
      class Student(private val value: Int , ) {
        def getValue: Int = value
      
        // Other methods and code for the class...
      }
      
      object Student {
        // Factory method to create instances of Student
        def apply(value: Int): Student = new Student(value)
      
        // Utility method provided by the companion object
        def myValue(a: Int, b: Int): Int = a + b
      }
      val obj1 = Student(42) // Equivalent to Student.apply(42)
      val obj2 = Student.apply(10) // Creating instances using the factory method
      
      val sum = Student.myValue(5, 7) // sum will be 12      
      
                       
                    

Conclusion

In this article of Scala class and object , we learn classes can also have other members such as methods, inner classes, companion objects, and more. Classes can be extended to create subclasses and participate in inheritance hierarchies, allowing for polymorphism and code reuse and overloading and OOPS concept.

Overall, classes play a central role in Scala's object-oriented programming paradigm, and they are used to define data structures and behaviors in a structured and reusable manner same as Java.