Scala Companion Object

A companion object in scala is an object that’s declared in the same file as a class and has the same name as class. So we can create an instance of class without new keyword.

In this post, we are going to see how we can use Scala companion object with an example.

Refer the below code, we define the case class Book and the corresponding companion object with two apply methods to provide multiple constructors for “Book” case class and the “apply” methods provide default values for the unavailable fields.

Refer the main method of MainScala object where we create an instance Book class without new keyword and the companion object apply method would be called by that time.



object MainScala {

  def main(args: Array[String]) = {

    val book1 = Book("title1", 100.0f, "author1")
    val book2 = Book("title2", 50.0f)
    println("book1: " + book1)
    println("book2: " + book2)
  }
}

case class Book(title: String, price: Float, author: String, publisher: String)

object Book {

  def apply(title: String, price: Float, author: String): Book = {

    val book = new Book(title, price, author, "")
    book
  }

  def apply(title: String, price: Float): Book = {

    val book = new Book(title, price, "", "")
    book
  }
}


The output of the above example is given below


book1: Book(title1,100.0,author1,)
book2: Book(title2,50.0,,)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s