Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to enhance a class with function delegation

I have the following classes in Scala:

class A {
    def doSomething() = ???

    def doOtherThing() = ???
}

class B {
    val a: A

    // need to enhance the class with both two functions doSomething() and doOtherThing() that delegates to A
    // def doSomething() = a.toDomething()
    // def doOtherThing() = a.doOtherThing()
}

I need a way to enhance at compile time class B with the same function signatures as A that simply delegate to A when invoked on B.

Is there a nice way to do this in Scala?

Thank you.

like image 918
hipjim Avatar asked Apr 24 '19 09:04

hipjim


1 Answers

In Dotty (and in future Scala 3), it's now available simply as

class B {
    val a: A

    export a
}

Or export a.{doSomething, doOtherThing}.

For Scala 2, there is unfortunately no built-in solution. As Tim says, you can make one, but you need to decide how much effort you are willing to spend and what exactly to support.

like image 186
Alexey Romanov Avatar answered Sep 23 '22 02:09

Alexey Romanov