lundi 9 janvier 2017

Is it possible to implement (in Scala) a polymorphic wrapper class that automatically implements the methods of the wrapped class?

I would like to implement a wrapper class similar to this:

class Wrapper[A](wrapped: A) {
  ...
}

And I would like it to behave like this:

val a: Wrapper[Int] = new Wrapper(2)
val b: Wrapper[Int] = new Wrapper(3)

val c = a + b  // "c" should be equal to Wrapper(5)
val d = a * b  // "d" should be equal to Wrapper(6)

val e: Wrapper[String] = new Wrapper("Hello ")
val f: Wrapper[String] = new Wrapper("World")

val g = e + f // "g" should be equal to Wrapper("Hello World")

But I do not want to manually implement the "+" and "*" methods inside the Wrapper class; because in general I do not know which methods the class A will have, and I want Wrapper to have all methods that A has, for any A.

Is this possible at all (in Scala)?

I suspect the answer is "no", but I would like to confirm. And if so, is there any alternative way to achieve this sort of generic behaviour?





Aucun commentaire:

Enregistrer un commentaire