Force initialization of Scala singleton object

后端 未结 4 1621
有刺的猬
有刺的猬 2020-12-15 08:16

I\'m working on an automatic mapping framework built on top of Dozer. I won\'t go into specifics as it\'s not relevant to the question but in general it\'s supposed to allow

4条回答
  •  旧巷少年郎
    2020-12-15 08:56

    In ended up doing this:

    trait ProjektionAware with DelayedInit
    {
      private val initCode = new ListBuffer[() => Unit]
    
      override def delayedInit(body: => Unit)
      {
        initCode += (() => body)
      }
    
    
      def registerProjektions()
      {
        for (proc <- initCode) proc()
      }
    }
    
    object A extends ProjektionAware {
      projekt[A].to[B]
    
    }
    

    Now I can use a classpath scanning library to initialize all instances of ProjektionAware on application bootstrap. Not ideal, but works for me.

提交回复
热议问题