延迟特性初始化 [英] Delaying trait initialization

查看:135
本文介绍了延迟特性初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个组件组合的智能机制,允许混合在traits中之后初始化组合组件。以下引发 NullPointerException

 类Component {
def addListener(pf:PartialFunction [Any,Unit]){}
}

trait DynamicComponent {
protected def component:Component

component.addListener {
case x =>
}
}

类Foo extends DynamicComponent {
protected val component = new Component
}

new Foo // - > NullPointerException

以下是我的不是选项




  • 使用 protected lazy val组件;这将产生一个 avalange 几十个vals需要变得懒惰,我不想

  • 放置 addListener 在方法中,例如 initDynamic();因为我会混合许多特质,我不想记得调用一半的 initFoo()方法。

  • 使用 DelayedInit 。这不适用于traits,至少根据scaladocs。



我可以用一个 init()调用,但仅在以下条件下:




  • 全部混合在traits中可以很容易地声明为在此一次调用中调用

  • 这是一个编译错误,忘记了 init()语句。


解决方案

您可以使用早期定义延迟trait的初始化。 (请参见 scala语言规范的第5.1.6节)



class Foo extends {
protected val component = new Component
} with DynamicComponent
pre>

I need a smart mechanism for component composition which allows mixed in traits to initialize after the composed component. The following throws a NullPointerException:

class Component {
  def addListener(pf: PartialFunction[Any, Unit]) {}
}

trait DynamicComponent {
  protected def component: Component

  component.addListener {
    case x =>
  }
}

class Foo extends DynamicComponent {
  protected val component = new Component
}

new Foo  // -> NullPointerException

The following things are not options for me:

  • Using protected lazy val component; that would produce an avalange of dozens of vals needing to become lazy, something I do not want.
  • Putting addListener in a method, e.g. initDynamic(); because I will be mixing in many traits, and I don't want to remember to call half a dozen initFoo() methods.
  • Using DelayedInit. This doesn't work with traits, at least according to the scaladocs.

I could live with a single init() call, but only under the following conditions:

  • all mixed in traits can easily declare to be invoked in this one single call
  • it is a compile error to forget the init() statement.

解决方案

You can delay the initialization of a trait by by using early definitions. (See section 5.1.6 of the scala language specification)

class Foo extends {
  protected val component = new Component
} with DynamicComponent

这篇关于延迟特性初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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