Way to enhance a class with function delegation

独自空忆成欢 提交于 2019-12-05 10:06:53

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.

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.

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