Way to enhance a class with function delegation

冷暖自知 提交于 2019-12-07 04:03:49

问题


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.


回答1:


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.




回答2:


You can avoid repeating the function signatures by making an alias for each function:

val doSomething = a.doSomething _
val doOtherthing = a.doOtherThing _

However these are now function values rather than methods, which may or may not be relevant depending on usage.

It might be possible to use a trait or a macro-based solution, but that depends on the details of why delegation is being used.




回答3:


Implicit conversion could be used for delegation like so

object Hello extends App {
  class A {
    def doSomething() = "A.doSomething"
    def doOtherThing() = "A.doOtherThing"
  }

  class B {
    val a: A = new A
  }

  implicit def delegateToA(b: B): A = b.a
  val b = new B
  b.doSomething() // A.doSomething
}


来源:https://stackoverflow.com/questions/55826206/way-to-enhance-a-class-with-function-delegation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!