Sorry for bringing this up again, but i believe there is still no solution? As of version 3.3 DelayedInit which is deprecated at this moment, is dropped as it seems? In all of the dropped features discussed there, some kind of alternative is given, but for DelayedInit
we are left in the dark.
Now the problem of actions after object creation were described most clearly in the first post by scabug in the discussion OnCreate trait: call onCreate method after object creation #4330 in 2011. The solution seemed as clear to me. But then it was decided to introduce DelayedInit
, which is now phased out. Subsequently it was discussed in the thread DelayedInit or OnCreate, any solution? started in 2018 by soronpo. A lot of use cases were presented, but no action was formulated.
Fast forward 5 years. Recently i stumbled on the problem myself: Having this library (scastie: super minimised):
abstract class Book :
def title: String
def content: String
/* Register each book at construction. */
Store.add(this)
object Store :
private var shelf: Map[String,Book] = Map.empty
def add(book: Book): Unit = shelf += book.title -> book
def list: Iterable[String] = shelf.keys
and the library user may then write
class PizzaBook(val owner: String) extends Book :
val title = "About Pizzas"
val content= "Start with some wheat ..."
but adding the book this way is not going to work, as null
as title is stored
val b1 = PizzaBook("Jan")
Of course, one can demand the user to register manually,
Store.add(b1)
but this can easily be forgotten.
You may also demand the library user to define the title
as class parameter
class CarBook(val title: String, val owner: String) extends Book :
val content= "The Ferrari ..."
so that one uses
val b2 = CarBook("My Ferrari","Piet")
but this cannot be enforced other then by adding the title
parameter to Book itself, and this
is not favourable in a lot of use cases.
Now, what is the magic trick that can be performed?