Scala object explained in detail

 200 total views,  2 views today

Welcome to Scala series. In this tutorial, you will learn about Scala object explained in detail.

Scala object explained in detail

Scala Object is a special type of class. It is a singleton class and it can have only one instance. We cannot create multiple instances of Object.

Scala Object is similar to Java Singleton class. In Java, we use the static keyword for a method. To access the static method we have to use the Class name, not by the object. But in Scala, we do not have a static keyword. We have to use Object and every method in Object is a static method.

Scala main method is always written in an Object class.

Syntax

object Test {

}

object Scala {
  def main(args: Array[String]): Unit = {
   //TODO
  }
}

Scala object with a method

This is a simple Object class with two methods. main() and add()

object Scala {
  def main(args: Array[String]): Unit = {
    println("This is main method")
  }

  def add(i: Int, j: Int) {
    i + j
  }
}

How to access methods in Object?

We cannot create an instance for the Object.

object Scala {
  def main(args: Array[String]): Unit = {
    println("This is main method")
  }

  def add(i: Int, j: Int) {
    i + j
  }
}

class Test {
  def test() {
    var scal = new Scala(); //compilation error - not found: type Scala
  }
}

Syntax to access a method: Classname.methodname

object Scala {
  def main(args: Array[String]): Unit = {
    println("This is main method")
  }

  def add(i: Int, j: Int) {
    i + j
  }
}

class Test {
  def test() {
    Scala.add(1, 2) // Accessing a method in Object
  }
}

Private methods in an Object

We can have private methods in an object class. But it cannot be accessed outside the class.

object Scala {
  def main(args: Array[String]): Unit = {
    println("This is main method")
    add(1,2)
  }

  private def add(i: Int, j: Int) {
    i + j
  }
}

class Test {
  def test() {
  // Error - method add in object Scala cannot be accessed in object Scala
    Scala.add(1, 2)
  }
}

Which scenarios can we use Object?

  • Database connection – In our application, to avoid multiple databases connect, we have to write a singleton class to always use the same instance. We have to use Object in this scenario.
  • Logging framework

References: https://docs.scala-lang.org/tour/singleton-objects.html

Thanks for reading and hope you like this tutorial. Please leave a comment and give us a thumbs up!

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.