given two classes:
abstract class ClassA(val argA:Int = 1) {
def func1 {
... argA ... //some operations
func2
}
def func2
}
class ClassB extends ClassA {
def func2 {
... argA ... //some operations
}
}
val b = new ClassB
b.func1
How can I pass argA=3 while instantiating b?
There will be dozens of child-classes like B, so it would be good if there were no need to rewrite
“(val argA:Int = 1)” in every class definition. Even in this case, things would be somehow obscure.
The most similar question I have found is about getting, not setting the value:
question
As you can see, there are several possible ways how to achieve what you asked for. However, it is not obvious which one is the best way, since that depends on what you’d like to put your emphasis on (conciseness, reuse, performance) and how your actual code looks. Some things worth having in mind are:
With solutions along the line of @maackle’s, each instantiation of the form
will result in an anonymous class
class AnonSubB extends ClassBthat is created behind the scenes. If you want to focus on conciseness, then this is probably the way to go, but the anonymous classes might slow down compilation if their number increases.@paradigmatic’s solution
is nearly as concise and does not result in anonymous classes, but has the disadvantage that the default value of
argAas specified byClassAis not reused (which it is in @maackle’s solution). You could repeat the value, i.e., declareClassBasbut this is error-prone, since you have to change the default value in various places, should it ever need to be changed.
I also like to offer a solution of my own, where the focus lies on reusing default values without creating anonymous classes, but which is less concise: