Scala objects

After seeing aboutclassandcase class, we are going to learn aboutobject.

I know, it is confusing, because we learned that anobjectis what we create when we instantiate aclass, but this term can also be used to talk about aclassthat do not need to be instantiated. I know, confusing…

To make it clearer, let's just focus on thoseobject. If you know other programming languages, you might have heard ofstatic, it means that thefieldandmethodcan be accessed without instantiating theclass. Let's talk about it more in the section after the exercise.

Did you notice how thefieldandmethodare being accessed ?

You use the name of theobject, for instance:Configuration.To accessKeyNumberOfFoosthat is defined inside ofConfiguration, you just have to do:Configuration.KeyNumberOfFoos. No need fornewor anything special, you can just call thememberof theObjectdirectly.

Objectare most commonly used when you want to defined constants values that are common for several systems orclasses, like theConfigurationone we have here.Objectare also used to stored “utility methods” or also called “helper methods“.

Thishelper methodsare common tools for several systems that do not have dependencies defined at runtime. That means that you can define the behavior of thismethodonly based on the input parameters, no need to know any more parameters. For instance, a method to sum two numbersa + b, you do not need to know more than the two inputs:aandb. They are self contained systems and can often be reused from one project to another as a library.

Reveal more information and clues
Load Exercise