Eliminate duplicate code whose only difference is the type

Viewed 93

I have two structurally-equivalent class pairs whose only difference is the types. I would like to be able to merge V1 with V2 and K1 with K2. I control those four classes, but I am not able to modify takesDoublesOrLists - it comes from a library.

class V1 (
    val a: Double,
    val b: Double,
    // ...
    val z: Double
)

class K1(v: V1) {
    def doIt = takesDoublesOrLists(v.a, v.b, /* ..., */ v.z)
}

class V2 (
    val a: List[Double],
    val b: List[Double],
    // ...
    val z: List[Double]
)

class K2(v: V2) {
    def doIt = takesDoublesOrLists(v.a, v.b, /* ..., */ v.z)
}

I tried following the type class pattern, but got an error that the overloaded method takesDoublesOrLists could not be applied to my type parameter.

Edit:

The signature of the overloaded function takesDoublesOrLists is as the name suggests:

def takesDoublesOrLists(a: Double, b: Double, /* ..., */ z: Double): Something = /* ... */
def takesDoublesOrLists(a: List[Double], b: List[Double], /* ..., */ z: List[Double]): Something = /* ... */
2 Answers
Related