Scala将方法转发或委托给封装的对象 [英] Scala forward or delegate methods to encapsulated object

查看:119
本文介绍了Scala将方法转发或委托给封装的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能将某些类方法隐式转发到封装的对象?

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
}

我要避免创建 def updateLastScanDate = lastScan.updateLastScanDate 将方法转发给包装的对象。

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

推荐答案

用简单的语言是不可能的。

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

他以前似乎在开发 Autorproxy重新启动 版本现在基于宏,因此可以直接包含在您的项目中。我在这里从其测试源粘贴一个示例:

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")

这篇关于Scala将方法转发或委托给封装的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆