06: Scala Class Vs. Object and Companion object interview Q&As

Q1. Given the below Person.scala file with Person.calss, what will be the output?

A1. It prints the below text as when a Scala class is instantiated the statements in the body are executed after the object is constructed via the constructor defined in the class signature itself as “Person(name: String, age: Int, salary: BigDecimal)”. The functions calcBonus(..), getNameLength(), etc apply to the objects (i.e. instances of a class) created with the “new” keyword.


Q2. How will you define static methods in Scala?
A2. Using an Object, which is a singleton. In the above example “Test” is an object, and it extends App so that you get the main method for free to run the application. The above code can be rewritten with the static main method.


Q3. As you can see in the above code we did not use the “new” keyword for the BigDecimal. Just define it as BigDecimal(250.00) or BigDecimal(25). How can we do the same for the Person class?
A3. This can be achieved by creating a “Companion Object” & then defining the apply(…) function in the companion object. A companion object in Scala is a singleton object created in the same file where the class resides with the same name.

For example, “object Person” is defined in the same Scala file Person.scala with the same name as class “Person”.

If you want to prevent the above code from using the “new” keyword at all, then define the Person class constructor as “private“.

Q4. How will you fix the print statement in the Person class to print the instance variable values as in “John”, 25, etc as opposed to the object instance value as in “com.sbthello.Person@330bedb4”?
A4. Convert the class to a case class, which gives you toString(..), hashCode(..), equals(..), apply(…) & unapply(..) functions for free as shown below. Companion object is not required.


Q5. How do you create multiple constructors in Scala?
A5. Using the this(..).


Note that the person2 object was created with the “new” keyword as in new Person(“Peter”, 42) using the auxiliary constructor with 2 args.

Q6. What if you don’t want to use the “new” keyword every time using an auxiliary constructor?
A6. Create a companion object with the apply(..) function.


800+ Java Q&As & tutorials