Scala Tutorial - Learn How To Declare Values And Fields In Companion Object

By Nadim Bahadoor | Last updated: July 25, 2017 at 14:17 pm

Overview

In this tutorial, we will learn how to declare values and fields in Companion Object which will be accessed only by the class of the Companion Object.

 

This tutorial builds on what you have learned from the previous tutorials on Learn How To Create And Use Companion Objects and Learn How To Use Companion Objects' Apply Method As A Factory (Class Hierarchy Via Inheritance)

Steps

1. How to define a simple class to represent a Donut object

If you have followed the two previous tutorials on Companion Objects as listed above, you should be familiar with the Donut class below which has a print() method.

 


println("Step 1: How to define a simple class to represent a Donut object")
class Donut(name: String, productCode: Option[Long] = None){

def print = println(s"Donut name = $name, productCode = ${productCode.getOrElse(0)}, uuid = ${Donut.uuid}")

}

NOTE:

  • But within the print statement above, we also print a unique ID for each donut as represented by the uuid field: uuid = ${Donut.uuid}
  • But where does the uuid field come from? Let's proceed to Step 2 below which shows the Donut Companion Object.

2. How to declare fields and values in Companion Object

Notice that within the Donut Companion Object, we've defined a value named uuid but also marked it as private.

 

If you have used another programming language such as Java or .NET in the past, it should be of no surprise that the private keyword would hide the visibility of the field uuid.

 

But, given that a Companion Object works along side the class to which the Companion Object refers to, even though the uuid field is not visible to the outside world, it is still accessible within the Donut class as shown in Step 2.


println("\nStep 2: How to declare fields and values in companion object")
object Donut {

 private val uuid = 1

 def apply(name: String, productCode: Option[Long]): Donut = {
  new Donut(name, productCode)
 }

 def apply(name: String): Donut = {
  new Donut(name)
 }
}

 

3. How to create instances of the Donut class using the Companion Object

Next let's create a couple of instances of Donut class using the Donut's Companion Object apply() method similar to what you've learned from the tutorial on Learn How To Create And Use Companion Objects.


println("\nStep 3: How to create instances of the Donut class using the companion object")
val glazedDonut = Donut("Glazed Donut", Some(1111))
val vanillaDonut = Donut("Vanilla Donut")

 

4. How to call function on each Donut object

When you call the print() method on each of the Donut instances, you will notice that the uuid value is also being printed in the console window.


println("\nStep 4: How to call function on each Donut object")
glazedDonut.print
vanillaDonut.print

You should see the following output when you run your Scala application in IntelliJ:


Step 4: How to call function on each Donut object
Donut name = Glazed Donut, productCode = 1111, uuid = 1
Donut name = Vanilla Donut, productCode = 0, uuid = 1

This concludes our tutorial on Learn How To Declare Values And Fields In Companion Object and I hope you've found it useful!

 

Stay in touch via Facebook and Twitter for upcoming tutorials!

 

Don't forget to like and share this page :)

Summary

In this tutorial, we went over the following:

  • How to define a simple class to represent a Donut object
  • How to declare fields and values in Companion Object
  • How to create instances of the Donut class using the Companion Object
  • How to call function on each Donut object

Tip

  • In upcoming tutorials, we will go over case classes which is a feature of Scala that will help you reduce boiler plate code by automatically generating accessors functions, hashCode and equals() methods.
  • What is more, case classes will also create companion objects for you!

Source Code

The source code is available on the allaboutscala GitHub repository.

 

What's Next

In the next tutorial, I will show you how to create and use Singleton Objects in Scala.

Nadim Bahadoor on FacebookNadim Bahadoor on GithubNadim Bahadoor on LinkedinNadim Bahadoor on Twitter
Nadim Bahadoor
Senior Software Developer | Elsevier
Founder of allaboutscala.com. I have over 10 years of experience in building large scale real-time trading systems in the financial industry. Passionate about Distributed Systems, Scala, Big Data and Functional Programming. Stay in touch for upcoming tutorials!
Other allaboutscala.com tutorials you may like:

Share this article on