11

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?

3
  • 1
    why not just ... val mongodb = ObjectB.url ...? Commented Mar 17, 2014 at 15:21
  • That does not work. The initialization logic that reads the values for the db credentials resides in another project and this another project which is a play application, on startup reads the config details and sends them to the ObjectA which is added as a dependency to the play project. The DAO classes that access the database reside in this dependency and they are not supposed to have any references back to ObjectB. Commented Mar 17, 2014 at 15:49
  • i believe you are looking for the Factory pattern. en.wikipedia.org/wiki/Factory_method_pattern Commented Mar 17, 2014 at 16:59

1 Answer 1

6

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)

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.