0

If I have a base class in Scala such as:

class Base(a: Int, b: Int, c: Int, d: Int, e: Int, f: Int = 1, g: Int = 2) {}

I want multiple classes to inherit from this base class, but I want to add arguments onto that list. Is there an efficient way to do this, without carrying around the massive argument list of the base class?

To make matters more complicated, the base classes may or may not redefine the optional parameters (f and g). Hypothetically:

class Child1(f: Int, h: Int, i: Int) extends Base(a,b,c,d,e,f)

And it of course would be something like

new Child1(a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9)

Is there a good way to do this in Scala? (I thought about passing a map through each constructors that defines the arguments, but then there's no compile-time checking of whether required parameters exist, and it relies on developers checking documentation to see what they should include. What if a key is misspelled? etc...)

mdenton8
  • 619
  • 4
  • 13

1 Answers1

2

If the number of the arguments of a constructor is that large,
as you don't want to repeat the arguments again in the definition,
then you should think about other pattern for the constructor.

You can read this SO question and its answer.
How many constructor arguments is too many?
The essence of the object-oriented programming does not change whether it's in Java or in Scala.

You can also use builder pattern (using a lot of setter methods and call the build() method), type-safe builder pattern with some amount of trade-off, or so.

Also, there was (and probably is) a limit on the number of tuple arity, case class constructor arguments, function parameters.
22 fields limit in case classes
Why are scala functions limited to 22 parameters?
I don't know whether it still exists, but the developers of Scala are trying to remove it.
[SI-7296] Remove arity limit for case classes - Scala
Nevertheless, it's a bad habit to make a function that has so many arguments.

At least, you can use/define tuples or case classes for each class to make the constructor simple, but it does not help for optional parameters. Or maybe curried constructor if you are familiar with functional languages...

Community
  • 1
  • 1
Naetmul
  • 11,923
  • 6
  • 46
  • 72