You have a misconception with the term Immutable:
I believe that its immutable as I can't edit the variables or access
them once its created
That's the definition of a private thing (method, variable, ...). Immutability refers to the fact that you cannot mutate state, that is, you can't change the value of something unless you create a new instance of it.
Let's see it with an example:
trait Foo{
def myMutableValue: Int
}
class Clazz extends Foo{
var myMutableValue = 1
def changeState(): Int = {
myMutableValue += 1
myMutableValue
}
}
val bar = new Clazz
bar.changeState() // myMutableValue = 2
bar.changeState() // myMutableValue = 3
bar.changeState() // myMutableValue = 4
bar.myMutableValue // myMutableValue = 4
With that example, in your instance of Clazz
(bar
) you're changing the state of a class attribute, in this case myMutableValue
is changing its value every time I invoke changeState
.
Please note that the class is public by default and changeState
is also public and that doesn't means that is immutable.
Now, let's see an immutable approach:
trait Foo{
def myMutableValue: Int
}
class Clazz extends Foo{
val myMutableValue = 1
def changeState(): Int = myMutableValue + 1
}
val instance = new Clazz
instance.changeState() // myMutableValue = 2
instance.changeState() // myMutableValue = 2
instance.changeState() // myMutableValue = 2
instance.myMutableValue // 1
With this approach, every call to changeState
will evaluate to 2, no matter how many times I call the function. That is, because we're dealing with an immutable value (val myMutableValue = 1
). Every invocation of changeState
will perform the evaluation and return a copy of that value. You're not modifying in any way the value of myMutableValue
.
Please take a look to this and this.
Also, please take a look at your code, you have some errors:
- By convention, class name should be capitalized (
Person
instead of person
).
- You don't need to reassign your class values with
def
(def getName
and def getDob
). You can use class values as is.
Lastly:
It also does not have final in front of it which is further making me
doubt myself.
Again, you're talking about different things. final
, as in Java, is a modifier to prevent your class to be extended
. It doesn't relate in any way to immutability In adition, if you want to prevent mutability in your subclass you have to make all their members final
(see this).
Since your example is coded in Scala you have all the tools that the language itself offers at your disposal (e.g. val
, sealed
, final
)
Please note that I've used a trait
to explain the possible use of def
.
EDIT: about final
modifier and immutability
Thanks to @Silvio Mayolo and @puhlen for the comments and clarification about final