Scala forward or delegate methods to encapsulated object

笑着哭i 提交于 2019-12-07 06:12:10

问题


Is there any possibility to implicitly forward some of class methods to encapsulated object?

case class Entity(id: Int, name: String,) {
  private lazy val lastScan = new LastScan

  def getLastScanDate    = lastScan.getLastScanDate
  def updateLastScanDate = lastScan.updateLastScanDate
}

I want to avoid creating def updateLastScanDate = lastScan.updateLastScanDate just to forward methods to wrapped object.


回答1:


In the plain language this is not possible. There used to be a compiler plugin by Kevin Wright to achieve this automatic delegation.

He seems to be working on an Autorproxy "Rebooted" version now that is macro based, making it straight forward to include in your project. I'm pasting here an example from its test sources:

trait Bippy {
  def bippy(i : Int): String
}

object SimpleBippy extends Bippy {
  def bippy(i: Int) = i.toString
}

@delegating class RawParamWrapper(@proxy pivot: Bippy)
val wrapper = new RawParamWrapper(SimpleBippy)
assert(wrapper.bippy(42) == "42")


来源:https://stackoverflow.com/questions/27035808/scala-forward-or-delegate-methods-to-encapsulated-object

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