DelayedInit or OnCreate, any solution?

Could that use case be satisfied by sourcecode.Name from GitHub - com-lihaoyi/sourcecode: Scala library providing "source" metadata to your program, similar to Python's __name__, C++'s __LINE__ or Ruby's __FILE__.?

1 Like

Very cool lib. I’ll try it out!

Just to expand on the use case in ScalaFX, the scalafx.application.JFXApp trait primarily does two things:

  1. Firstly, it initializes JavaFX and starts the JavaFX Application Thread (JFXAT), using any supplied command line arguments.
  2. It then uses scala.DelayedInit to queue up all sub-class constructors (in the exact same manner as with scala.App) but then passes them for execution to the JFXAT.

This is extremely convenient, because interaction with the JavaFX API must typically take place only on the JFXAT. This allows ScalaFX users to write trivial GUI applications in their application constructors, safe in the knowledge that the JFXAT will have been created and initialized, and that those constructors execute on that thread too.

For example:

import scalafx.Includes._
import scalafx.application.JFXApp
import scalafx.scene.Scene
import scalafx.scene.paint.Color._
import scalafx.scene.shape.Rectangle

object HelloStageDemo
extends JFXApp {
  stage = new JFXApp.PrimaryStage {
    title.value = "Hello World!"
    width = 600
    height = 450
    scene = new Scene {
      fill = LightGreen
      content = new Rectangle {
        x = 25
        y = 40
        width = 100
        height = 100
        fill <== when(hover) choose Green otherwise Red
      }
    }
  }
}

Without DelayedInit, all bets are off. Even onCreate doesn’t appear to address how this can be resolved. The only solution appears to be to put what used to be in the constructor into a virtual function, and hope that no-one attempts to interact with JavaFX from an application constructor. This a far less elegant, and would break all existing user code too.

4 Likes

I would like to add my own use-case for DelayedInit, perhaps contributing to the argument that it used in more cases than just a few niche ones. In my use case I’m trying to add an ability to chain test cases written with ScalaTest. I’ll let the code explain it:

import com.typesafe.scalalogging.StrictLogging
import org.scalatest._

import scala.collection.mutable

/**
  * A mixin (fun) suite which introduces the concept of chained tests; a chained test will be first executed like any
  * other test in the suite, but after all the "normal" executions are done, the chained test will be executed in pairs
  * with each of the other chained tests in the suite (including itself).
  *
  * For instance, if the suite has 2 "normal" tests (1, 2) and 3 chained tests (3, 4, 5), then first all the tests will
  * be executed normally (1, 2, 3, 4, 5). Afterwards, each pair possible to construct from the chained tests will be
  * executed as an individual test; a test of 3 and then 3, a test of 3 and then 4, 3 and then 5, 4 and then 3, etc
  * (total of 3 * 3 = 9 additional tests).
  *
  * This is especially useful when testing units which are stateful by their nature, since it is vital to assert that
  * the unit is capable of executing separate use-cases in succession without breaking its inner state.
  */
trait ChainedTestsSuite extends DelayedInit with StrictLogging {
  self: FunSuiteLike =>

  /* --- Data Members --- */

  private val tests = mutable.Buffer.empty[ChainedTest]

  /* --- Methods --- */

  /* --- Public Methods --- */

  override def delayedInit(suiteBody: => Unit): Unit = {

    suiteBody

    for (testA <- tests; testB <- tests) {
      test(s"Chain test: ${testA.order} and then ${testB.order}") {
        logger.info(s"Executing first test: ${testA.name}")
        testA.testFun()
        betweenChainedTests()
        logger.info(s"Executing second test: ${testB.name}")
        testB.testFun()
      }
    }
  }

  /**
    * Override this in order to execute code between two chained tests.
    */
  def betweenChainedTests(): Unit = {}

  /* --- Protected Methods --- */

  /**
    * Registers a test as a chained test.
    *
    * @see [[FunSuiteLike.test]]
    */
  protected def chainTest(testName: String, testTags: Tag*)(testFun: => Unit): Unit = {

    val order = tests.size + 1
    val chainedName = s"($order) $testName"

    test(chainedName, testTags: _*)(testFun)
    tests += ChainedTest(chainedName, order, () => testFun)
  }
}

object ChainedTestsSuite {

  /* --- Inner Classes --- */

  private case class ChainedTest(name: String, order: Int, testFun: () => Unit)

}

I’m guessing this is an ability that could be added to ScalaTest without the need to use DelayedInit, but for someone who wants to “act quickly” this is sometimes a viable feature of the language.

I take the chance to add another use case. We have test classes that implement certain life-cycle methods. In delayedInit the life-cycle methods are called in proper sequence including the actual test code:

**
  * Base trait for tests that takes care that the life-cycle methods of a test are called in proper sequence.
  *
  * Required components can be mixed into this trait. Read the documentation of the [[WithLifecycle]] trait
  * carefully in order to implement proper startup and shutdown sequences.
  */
trait InnerTest extends WithLifecycle with WithLog with DelayedInit {

  override def delayedInit(testCode: => Unit): Unit = {

    tryFinally {
      log.debug(s"before inner test - class: ${getClass.getSimpleName}")
      startup()
      log.debug(s"execute inner test - class: ${getClass.getSimpleName}")
      testCode
      log.debug(s"shutdown inner test - class: ${getClass.getSimpleName}")
      shutdown()
      log.debug(s"wait for completion of inner test - class: ${getClass.getSimpleName}")
      waitForCompletion()
      log.debug(s"inner test completed regularly - class: ${getClass.getSimpleName}")
    } {
      log.debug(s"cleanup inner test - class: ${getClass.getSimpleName}")
      cleanup()
      log.debug(s"after inner test - class: ${getClass.getSimpleName}")
    }
  }

}

We also use this type of dsl. I think with static scope injection and implicit function type (

)
It can be done better.

See also the dedicated thread that @etorreborre opened about specs2: Scala 3: DelayedInit

(but please continue the discussion here, instead)

This is now the ‘official’ thread related to removal of DelayedInit in Scala 3, as part of the first Scala 3 SIP batches. See First batch of Scala 3 SIPs

After some thoughts on this subject lately. Probably some use-cases can be satisfied with the addition of trait parameters. My use cases still require some sort of a post-constructor call. I propose the following OnCreate replacement.


trait AnyRef {
  // ....
  def OnCreate : this.type = this
}

The users can override OnCreate:

trait Foo {
  override def OnCreate : this.type = {
    //Some changes here
    this //either mutate this or return a new object
  }
}

Because the compiler identifies an overridden OnCreate then

new Foo {}

will be replaced with

new Foo {}.onCreate

Note: this is of course for cases where the end-users directly requiring interacting with new, so a companion object’s constructor is not enough to get the job done.

It is very often requiring when we use dsl.
And in such case

The above code is very bad decition.

Is there any plan to implement static scope injecitoion?

With that feature I will remove ‘new’ operator from my dsl with great pleasure.

@etorreborre Since Before/After are the real users of DelayedInit, and they’ve caused confusion before, have you considered deprecating them? Standard usage of Scope doesn’t require DelayedInit, right? It’s mostly the AOP-style before/after hooks.

Is it correct to summarize this as JFX being a shared resource that must be initialized before usage, and that should only be used through a well-defined entry point?

Sounds kind of like ExecutionContext or similar context that’s made available implicitly. Could the JFXApp supply the implicit, which is then consumed by everything needing access to it? Or just some lazy val that’s inherited from JFXApp, and some way of enforcing that all JFX access goes through it?

May be it is more closer to builder pattern.

It is not always comfortable In common case of builder pattern.
Because if grammar of builder is complex,
it is very important to have the ability to use context dependency.
For example it is very comfortable when method setImage is accessible only from ImageView.

Regarding static scope injection, I think it could be subsumed by methods defined in an outer scope that take an implicit argument to enforce that they can only be called in the scope of an implicit function.

Something like (very roughly, sorry):

trait JFXDsl {
   type JFX[T] = implicit JFXAT => T
   def stage(...): JFX[...] { /* the implicit arg of type JFXAT gives you access to the JavaFX subsystem*/ }
}

trait JFXApp extends JFXDsl {
  implicit lazy val jfx: JFXAT = initializeJFX
}

class MyJFXApp extends JFXApp {
  // stage implicitly gets the jfx context from JFXApp, 
  // can't be called without a JFXAT around
   stage(....) 
}

// alternatively, you can write code, and as long as the expected type is JFX[T], 
// it will be lifted to a closure that abstracts over the missing JFXAT argument
2 Likes

The implicit function type docs have a nice example on how to implement the Builder pattern: https://dotty.epfl.ch/docs/reference/implicit-function-types.html

If I understand it correctly it works well only in simple case.

With such approach we must:

  • make manual import of grammar (import SomeClass._)
  • cares that different inner method will not have same name

In may experence the

   new SomeClass{
       ...
   }

More comfortable and scalable now.

@adriaanm In my own DSL use-case, I use lazy values for this purpose. However, I’m missing an ability to annotate a definition/value so it can only be accessed from outside the class (meaning, post-construction). E.g.,

package MyLib
class Foo {
  @post[MyLib] lazy val dontTouchInside : Int = ???
}

Foo is library class that I’m exposing to users from which they can inherit.
The dontTouchInside lazy value must only be accessed post-construction of Foo or internally with [MyLib] privileges. In other words:

new Foo{}.dontTouchInside // should compile
new Foo { dontTouchInside} //should not compile when not in package MyLib

It can be real headache for such words like width, caption and so on. When your code works well until you do some more imports :frowning:

Could the internal and external facing members be different? The one that requires Foo be initialized, could take an implicit argument that’s made available by a factory method that creates Foo instances? It’s an interesting conundrum that this: Foo is more restricted than foo: Foo in terms of the capabilities it unlocks.

Sorry, I don’t understand. The example I mentioned does not contain any imports. One way to think of it is that you enforce scoping through the availability of implicit arguments, instead of nesting the definitions (which would indeed then require them to be imported).