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

后端 未结 2 438
予麋鹿
予麋鹿 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.

    0 讨论(0)
  • 2020-12-25 13:10

    Extending FunctionXX is another way of achieving the goal; it might have an advantage of providing better documentation. Both parameter types and return value type are visible on the first line of the declaration:

    val activeUser = new Function0[List[String]] {
      val users = getUsersFromDB
      def apply = users filter (_.active)
    }
    
    0 讨论(0)
提交回复
热议问题