DelayedInit or OnCreate, any solution?


#41

My actual usage is in a embedded DSL (SpinalHDL), it use DelayedInit/onCreate to automaticaly build a component hierarchy from the user code execution:

//embedded DSL core
object Component{
   val componentStack = mutable.Stack[Component]()
}

class Component extends OnCreate{
  val children = ArrayBuffer[Component]()
  val parent = Component.componentStack.head()
  parent.children += this

  Component.componentStack.push(this)
  
  //Automatic callback after the whole object construction
  def onCreate() = Component.componentStack.pop() 
}

//User code
class UserSubComponent extends Component{
  //behaviour code
}

class UserComponent extends Component{
  //behaviour code
  val subA = new UserSubComponent() //subA automaticaly know his parrent component via the componentStack, and it will automaticaly add itself to the UserComponent children list.
  val subB = new UserSubComponent()
}

It is also used in some other similar cases.