Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Parameters to Scala Object

Tags:

scala

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?

like image 735
joesan Avatar asked Mar 17 '14 14:03

joesan


1 Answers

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)

}
like image 105
dk14 Avatar answered Oct 19 '22 10:10

dk14