Romi Kuntsman Romi Kuntsman - 1 month ago 6
Scala Question

Scala - create class, inherit partial constructor parameter

In Scala, I want to create an abstract class, which accepts some "strategy" parameter (here

myBase
), and a value parameter (here
myVal
).
I want to inherit from that class, providing the strategy parameter as part of the inheritance, and get a class (here
Cls1
) which accepts the value as a constructor parameter.

Here's the code I want to be able to run:

abstract class Base(myBase: Int)(val myVal: Int) {
val divVal: Int = myBase / myVal
}

class Cls1 extends Base(10) // myBase = 10
val obj1 = new Cls1(5) // myVal = 5
assert(obj1.divVal == 10/5)


Unfortunately, I get the following errors:


Error: too many arguments for constructor Cls1: ()A$A58.this.Cls1 lazy val obj1 = new Cls1(5)
Error: missing argument list for constructor Base in class Base class Cls1 extends Base(10)


Can you please explain how can I accomplish this without repeating the logic (here
myBase / myVal
)?

Thanks!

Answer

You can require myVal to be an abstract field which has to be filled by any inherting class:

abstract class Base(myBase: Int) {
  val myVal: Int
  val divVal: Int = myBase / myVal
}

class Clazz(val myVal: Int) extends Base(10)

val clz = new Clazz(5)
assert(clz.divVal == 10 / 5)