将参数传递给 Scala 对象 [英] Pass Parameters to Scala Object
问题描述
是否有可能从外部对象初始化 Scala 对象?我尝试初始化的 Scala 对象没有任何 Companion 类.举个例子:
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
....
....
}
但是 MongoDBConnectionURI 类型的 mongoDBConnectionURI 需要一个主机和一个端口,我必须从配置文件中读取该配置文件,该文件实际上由对象 B 完成,并且这些值被传递给 ObjA.稍后我所有的 DAO 对象将访问对象 A 中的 mongoDBConnectionURI 变量以获取连接字符串.如何将值从对象 B 传递到对象 A 并初始化对象 A 中的值?
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?
推荐答案
简单的解决方案:
object ObjectA {
lazy val mongoDBConnectionURI = getConnection(name.get, passwd.get)
var name: Option[String] = None
var passwd: Option[String] = None
}
如果您在传递"名称和密码后使用 mongoDBConnectionURI - 一切都应该正常工作.但我建议使用类而不是对象并将其传递给 DAO 类(也没有循环引用):
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)
}
这篇关于将参数传递给 Scala 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!