This topic has been discussed before but not answered satisfactorily (in my opinion). Consider the following scala code:
class A(a:Int) { val _a=a }
class A1(val a:Int) { val _a=a }
class B(a:Int) extends A(a) // OK
class C(val a:Int) extends A(a) // OK
class B1(a:Int) extends A1(a) // OK
class C1(val a:Int) extends A1(a) // fails
class D1(override val a:Int) extends A1(a) // OK
I believe that declaring the class parameter as val only has an effect on the constructor call: the parameter is copied instead of passing a reference. However in each case the class field is allocated as a val. is this correct?
Now what I do not understand is why we need the override keyword in the last line. Note that we do not declare the classes as case classes so no automatic allocation of fields is going on.
Finally is there a good reason why one even would want to define a class like A1 with a val class parameter?
Thanks in advance for all replies.
I believe that declaring the class parameter as val only has an effect on the constructor call: the parameter is copied instead of passing a reference. However in each case the class field is allocated as a val. is this correct?
Not at all.
If there is a val or var in the constructor, that causes a val or var of the same name to be declared in the class, and assign the constructor parameter to it at construction. Otherwise, a (private) val may still be created in the class, if the constructor parameter is used outside initialization, i.e in a method.
In class A1, the member _a is really useless, because if you write
class A1(val a: Int) {}
it is equivalent to
class A1(someFreshName: Int) {val a = someFreshName}
So in C1
, you are trying to declare a new member a, while there is already one. Hence the override.
In your particular instance, both member would have the same value, but you could well do (maybe not a good idea)
class C1(override val a: Int) extends A1(12)
Then, the new member a
would have the constructor parameter as value, and the previous a
would have value 12 and be hidden (but still, code written in A1
would access it).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With