Romi Kuntsman Romi Kuntsman - 5 months ago 35
Scala Question

Scala - create class, inherit partial constructor parameter

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

), and a value parameter (here
I want to inherit from that class, providing the strategy parameter as part of the inheritance, and get a class (here
) 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



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)