In Scala, how would you declare static data inside a function?

后端 未结 2 437
予麋鹿
予麋鹿 2020-12-25 12:35

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

2条回答
  •  时光说笑
    2020-12-25 12:46

    Another option would be using a closure:

    object Example {
       val activeUsers = {
           val users = getUsersFromDB
           () => users.filter(_.active)
       }
    }
    

    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()

    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.

提交回复
热议问题