在许多情况下,我发现我需要在函数的范围内创建长寿命值,并且不需要将此数据放在类/对象范围内.
例如,
object Example {
def activeUsers = {
val users = getUsersFromDB // Connects to the database and runs a query.
users.filter(_.active)
}
}
Run Code Online (Sandbox Code Playgroud)
上面,变量users在正确的范围内,但每次activeUsers调用函数时它都会执行数据库查询.
为了避免这种情况,我可以将变量移到users函数范围之外:
object Example {
val users = getUsersFromDB // Connects to the database and runs a query
def activeUsers = {
users.filter(_.active)
}
}
Run Code Online (Sandbox Code Playgroud)
但这也使其可用于其他功能.
否则,我可以创建一个单独的对象来包含该函数:
object Example {
object activeUsers {
val users = getUsersFromDB // Connects to the database and runs a query.
def apply() = …Run Code Online (Sandbox Code Playgroud) 这是我之前的初始化变量问题的后续问题.
假设我们正在处理这种情况:
object AppProperties {
private var mgr: FileManager = _
def init(config: Config) = {
mgr = makeFileManager(config)
}
}
Run Code Online (Sandbox Code Playgroud)
此代码的问题在于AppProperties可能重新分配任何其他方法mgr.是否有一种技术可以更好地封装,mgr以便感觉像val其他方法一样?我想过这样的事情(灵感来自这个答案):
object AppProperties {
private object mgr {
private var isSet = false
private var mgr: FileManager = _
def apply() = if (!isSet) throw new IllegalStateException else mgr
def apply(m: FileManager) {
if (isSet) throw new IllegalStateException
else { isSet = true; mgr = …Run Code Online (Sandbox Code Playgroud)