Scala: Two classes with identical implementation

Viewed 73

I came across some code written in Scala that has the following structure

// a.scala
object A {
    def apply(arg: String) = {
         new A(arg)
    }
    // declare a bunch of constants
    val SOME_CONSTANT_A = "some_constant_a"
}

class A {
   // define functions that use SOME_CONSTANT_A and the other constants.
}

We now have b.scala which is has object B with different constants and the exact same body of class A duplicated as class B(class B uses the constants inside object B).

What is the best way to refactor this code? I'd like to just have a single class, and have its behavior change based on the object somehow.

1 Answers

Definition:

class Base(private val constant: String) {
  def printConstant(): Unit = println(constant)
}

class A extends Base("constant_for_a")
class B extends Base("constant_for_b")

Usage:

val a1 = new A()
a1.printConstant()
// constant_for_a

val b1 = new B()
b1.printConstant()
// constant_for_b
Related