将参数传递给 Scala 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22457278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass Parameters to Scala Object
提问by sparkr
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:
是否有可能从外部对象初始化 Scala 对象?我尝试初始化的 Scala 对象没有任何 Companion 类。这是一个例子:
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?
但是 MongoDBConnectionURI 类型的 mongoDBConnectionURI 需要一个主机和一个端口,我必须从配置文件中读取该配置文件,该文件实际上由对象 B 完成,并且这些值被传递给 ObjA。稍后我所有的 DAO 对象将访问对象 A 中的 mongoDBConnectionURI 变量以获取连接字符串。如何将值从对象 B 传递到对象 A 并初始化对象 A 中的值?
采纳答案by dk14
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):
如果在“传递”名称和密码后使用 mongoDBConnectionURI - 一切都应该正常。但我建议使用类而不是对象并将其传递给 DAO 类(也没有循环引用):
==moduleA==
class UserDAO(objectA: ObjectA)
==moduleB==
object ObjectB {
val user = ...
val passwd = ...
val a = new ObjectA(name, passwd)
object UserDAOInstance extends UserDAO(a)
}

