Is it ever possible to initialize a Scala object from an external object? The Scala object that I'm trying to initialize does not have any Companion class. Here it is as an example:
object ObjectA {
val mongoDBConnectionURI = // This is the Val that I want to initialize from an external object
....
....
}
But the mongoDBConnectionURI which is of type MongoDBConnectionURI needs a host and a port that I have to read from a config file which is actually done by Object B and these values are passed to ObjA. Later all my DAO objects will access the mongoDBConnectionURI variable in Object A to get the connection string. How could I pass the values from Object B to Object A and have the vals in Object A initialized?
Simple solution:
object ObjectA {
lazy val mongoDBConnectionURI = getConnection(name.get, passwd.get)
var name: Option[String] = None
var passwd: Option[String] = None
}
If you use mongoDBConnectionURI after "passing" name and password - everything should work fine. But i'd recommend to use class instead of object and pass it to the DAO classess (also without cyclic references):
==moduleA==
class UserDAO(objectA: ObjectA)
==moduleB==
object ObjectB {
val user = ...
val passwd = ...
val a = new ObjectA(name, passwd)
object UserDAOInstance extends UserDAO(a)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With