Maarten
Maarten

Reputation: 239

Scala: Is it possible to define a class that extends its class parameter?

I want to design a class that serves as a wrapper around any other class. Let's call this wrapper class Virtual and it is used as follows:

val x: String = "foo"
val y: Virtual[String] = new Virtual(x)
// any method that can be called on x can also be called on y,
// i.e., Virtual[String] <: String

// example:
y.toUpperCase // will change the wrapped string to an upper case

This is what I have so far:

class Virtual[T](obj: T) extends T {
  // any Virtual specific methods here
}

Extending the type parameter does not seem to do the trick...

In other words: How can I ensure that the methods exposed by the class wrapped by Virtual are also exposed by the Virtual class itself?

Upvotes: 2

Views: 93

Answers (1)

Mario Galic
Mario Galic

Reputation: 48430

As suggested in comments and in Kevin's answer, try using implicit conversion like so

object Hello extends App {
  class Virtual[T](val delegate: T) {
    def bar(i: Int): Int = i + 1
  }
  implicit def VirtualToDelegate[T](virtual: Virtual[T]): T = virtual.delegate
  val str = "foo"
  val virtual = new Virtual[String](str)
  println(virtual.toUpperCase) // FOO
  println(virtual.bar(7))      // 8
}

Upvotes: 2

Related Questions