Skip to content

OnCreate trait: call onCreate method after object creation #4330

@scabug

Description

@scabug

The DelayedInit trait addresses a rather small niche use case.
The following concerns the problem of calling code (automatically
and implicitly) after an instance has been created but prior to use.
This is useful for frameworks that want to enforce a on-creation
life cycle behavior.

It is always a problem of enforcing a on-creation behaviour
on a class hierarchy. The base class could have code that
gets executed in its constructor:

abstract class Base {
  // ...
  Framework.register(this)
}

but the complete object has not yet been constructed.
The Base class could wrap the code in a method which is called
in the constructor of a derived class

abstract class Base {
  // ...
  def onCreation: Unit=
    Framework.register(this)
}
class Derived extends Base {
  // ...
  onCreation
}

But, the Derived class might be further extended.

The proposed solution is to have a OnCreate trait similar to the
DelayedInit trait:

trait OnCreate {
    def onCreate: Unit
}
abstract class Base extends OnCreate {
  // ...
  def onCreate: Unit = {
    Framework.register(this)
  }
}
class Derived extends Base {
}


// the onCreate method is called after the Derived class is constructed
val d = new Derived

We all know when object construction starts but having code that
executes after an object is created, without being explicit about it,
is not possible.

It is the inclusion of the OnCreate trait that causes the compiler to
generate code that calls the onCreate method after construction
is completed.

// compiler generated code
val d = { val obj = new Derived; obj.onCreate; obj }

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions