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.
For ex
Another option would be using a closure:
object Example {
val activeUsers = {
val users = getUsersFromDB
() => users.filter(_.active)
}
}
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()
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
).
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.