在 Scala 中,如何在函数内声明静态数据? [英] In Scala, how would you declare static data inside a function?
问题描述
在许多情况下,我发现我需要在函数的作用域内创建长期存在的值,而这些数据不需要在类/对象作用域内.
In many situations I find that I need to create long-living values inside a function's scope, and there is no need for this data to be at class/object scope.
例如
object Example {
def activeUsers = {
val users = getUsersFromDB // Connects to the database and runs a query.
users.filter(_.active)
}
}
上面,变量users
在正确的范围内,但是每次调用activeUsers
函数时它都会执行一次数据库查询.
Above, the variable users
is in the correct scope, but it will execute a database query everytime the function activeUsers
is called.
为了避免这种情况,我可以将变量 users
移到函数范围之外:
To avoid this, I could move the variable users
outside the function's scope:
object Example {
val users = getUsersFromDB // Connects to the database and runs a query
def activeUsers = {
users.filter(_.active)
}
}
但这也使其可用于其他功能.
But that makes it available to other functions as well.
否则,我可以创建一个单独的对象来封装函数:
Else, I could create a separate object to enclose the function:
object Example {
object activeUsers {
val users = getUsersFromDB // Connects to the database and runs a query.
def apply() = {
users.filter(_.active)
}
}
}
但这涉及更多样板代码、使用另一个对象以及与 apply
相关的轻微语法奇怪.
But this involves more boilerplate code, use of another object and slight syntax oddities related to apply
.
- 是否在语言层面支持这样的事情?
- 如果没有,您在这种情况下是否使用任何标准技术?
推荐答案
另一种选择是使用闭包:
Another option would be using a closure:
object Example {
val activeUsers = {
val users = getUsersFromDB
() => users.filter(_.active)
}
}
说明
activeUsers
是 Function1[Unit, ...your filter result type...]
类型的变量(或者我们可以将此类型写为 (Unit => ...你的过滤结果类型...)
,这是一样的),就是这个变量存储了一个函数.因此,您可以稍后以与函数无法区分的方式使用它,例如 activeUsers()
Explanation
activeUsers
is a variable of type Function1[Unit, ...your filter result type...]
(or we can write this type as (Unit => ...your filter result type...)
, which is the same), that is this variable stores a function. Thus you may use it later in a way indistinguishable from function, like activeUsers()
我们用一段代码初始化这个变量,我们在其中声明变量 users
并在匿名函数 () => 中使用它.users.filter(_.active)
,因此它是一个闭包(因为它有一个绑定变量 users
).
We initialize this variable with a block of code where we declare variable users
and use it inside an anonymous function () => users.filter(_.active)
, hence it is a closure (as it has a bound variable users
).
因此,我们实现了您的目标:(1) activeUsers
看起来像一个方法;(2) users
计算一次;(3) filter
适用于每次调用.
As a result, we achieve your goals: (1) activeUsers
looks like a method; (2) users
is calculated once; and (3) filter
works on every call.
这篇关于在 Scala 中,如何在函数内声明静态数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!