Scala Companion object

 221 total views,  2 views today

Welcome to Scala series. In this tutorial, you will learn about Scala Companion object.

Before learning Scala companions, let us know a bit about Scala class and objects. I have already written a brief tutorial for Scala class and Scala object. Please check out those before proceeding with this tutorial.

Let us see the basics of Scala Class and Object.

Scala Class

A Class is a blueprint of an object.A Class can have fields, methods, constructors, extends another class or implement an interface or Trait.

class StaticReference {
  var i: Int = 1;
  var j: String = "a";
}

Object creatonion
var staticReference = new StaticReference(); //option 1
var staticRef2:StaticReference = new StaticReference(); //option 2

Scala Object

Scala Object is a special type of class. It is a singleton class and it can have only one instance. In Scala, we don’t have a static keyword, but to create static methods, we have to use Scala 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() {
    Scala.add(1, 2) // Accessing a method in Object
  }
}

Scala Companions

When a class and an object have the same name, then it is called a companion object.Both the class and the object should be in the same source file.

class Test {

}
object Test {

}

Scala companion object example

class Test {

  def run() {
    println("Test class  -> run")
  }
}
object Test {
  def main(args: Array[String]): Unit = {

    var test = new Test();
    test.run();
    Test.add();
  }

  def add() {
    println("Test Object -> add")
  }
}

Output

Test class  -> run
Test Object -> add

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!.