Hey everyone, I’m back with another blog, “Combating Fallacy in Scala: Part 3“. So, in this blog, we will have a look into Classes in Scala and the Constructor Parameters.
Class and Constructor Parameters
Before moving to the problem in this blog, let’s have a look at classes in Scala.
According to the Scala Docs “Classes in Scala are blueprints for creating objects. They can contain methods, values, variables, types, objects, traits, and classes which are collectively called members.”
Also, a class can have public, protected or private access modifiers. Public members are accessible from outside the class whereas that is not true for private members.
Moving to the constructors, a class always has a constructor(initializes objects of a class). When a constructor is not defined, the class still has a default constructor with no arguments and in case it is defined then we have some variables which we can initialize at the time of creating an object.
Let’s have a look at a class with its constructor to understand how it is created.
Now, let’s consider a scenario where I want to access the constructor variables outside of class. I’ll give you 2 options for this and you have to pick the correct one.
What do you think? In which one I’ll be able to access the constructor variables from outside the class and why so?
Time to Reveal
The correct option is Option 1.
The reason for that is the access modifiers associated in both the cases. When there is no val(Option 2) with the constructor variables then the parameter is considered as private and as I told you private members are not accessible from outside.
But when there is val with constructor parameter(Option 1), then it is considered as public and thus accessible from outside the class.
If we define our class as in Option 2, and if we have use case same as the scenario then a workaround can be the following:
But the way in Option 1 will be preferable.
Note: You can use var in place of val as well.
So that’s all for this blog. You can have a look at other blogs in the series.
I hope it was helpful and if there is any feedback please leave it in the comment section below.
Au Revoir 😊