0

I want to create a singleton object for my application , but i want to initialize it from another object.

For ex :

object A{
 val x = 10
 val b = B(x)
}

object B(y:Int){
var z = y
}

But this would not work , since object doesnt have constructor. I need to initialize object from another object since val x (in above example) would be known at runtime.

Any workaround for this?

Alok
  • 1,374
  • 3
  • 18
  • 44
  • 1
    Possible duplicate of [How do I initialize object vals with values known only at runtime?](http://stackoverflow.com/questions/8782448/how-do-i-initialize-object-vals-with-values-known-only-at-runtime) – Johny T Koshy Feb 23 '16 at 07:53
  • Duplicate of http://stackoverflow.com/q/27801150/1296806 but it's not a great use case, b/c you want to avoid thinking about init order. – som-snytt Feb 23 '16 at 08:39

2 Answers2

1

An Object does not have a constructor because it is initialized statically (as soon as it's loaded). What you're probably looking for is a plain class:

class B(y: Int) {
  var z = y
}

If you really need a singleton, why would you need to initialize it from a different object?

irundaia
  • 1,720
  • 17
  • 25
  • I need to initialize it from another object , because property of a singleton object would be known at runtime. And it is requirement of application to have a singleton object – Alok Feb 23 '16 at 08:19
  • Then why don't you simply change the value of the property at the creation of the other object? – irundaia Feb 23 '16 at 08:29
  • Thats an option . But i was thinking if there would be any cleaner way. thanks for suggestions:) – Alok Feb 23 '16 at 08:33
0

Objects in scala are lazily loaded, meaning they will only be instantiated once needed.

If you do not use the object before the wanted constructor call you could simply have an init function to act as a constructor, the object will be instantiated then.

Or Zilberman
  • 161
  • 4