官术网_书友最值得收藏!

  • Learn Scala Programming
  • Slava Schmidt
  • 259字
  • 2021-06-10 19:35:48

Local functions

Here is an example of two functions that are local to the enclosing method:

def average(in: Int*): Int = {
def sum(in: Int*): Int = in.sum
def count(in: Int*): Int = in.size
sum(in:_*)/count(in:_*)
}

In this example, we have both sum and count defined inside of the average definition, which makes them inaccessible from the outside:

scala> :type sum
^
error: not found: value sum

scala> :type count
^
error: not found: value count

As already mentioned, the function does not need to be nested in another method. The enclosing block can be of any kind, for example, a variable definition. For instance, consider if the average function from the previous example was only defined in order to calculate a single average:

val items = Seq(1,2,3,4,5)
val avg = average(items:_*)

We could rewrite both code blocks as follows:

val items = Seq(1,2,3,4,5)
val avg = {
def sum(in: Int*): Int = in.sum
def count(in: Int*): Int = in.size
sum(items:_*)/count(items:_*)
}

The scope visibility rules apply for methods the same way as for other language constructs. Because of this, the parameters of the outer method are visible to the inner functions and don't need to be passed explicitly. We can rewrite our first example again using this rule, as follows:

def averageNoPassing(in: Int*): Int = {
def sum: Int = in.sum
def count: Int = in.size
sum /count
}

There is a special name for the functions that refer to the definitions from the enclosing block, closures. Let's discuss them a little more deeply.

主站蜘蛛池模板: 丹东市| 理塘县| 景宁| 晴隆县| 阜新市| 尚义县| 湘西| 高淳县| 额尔古纳市| 乃东县| 桐柏县| 大洼县| 阳西县| 繁峙县| 信阳市| 安岳县| 临湘市| 商河县| 玉山县| 海伦市| 东台市| 巴林右旗| 临安市| 惠安县| 饶河县| 凤翔县| 瑞昌市| 屯留县| 阳朔县| 安远县| 岗巴县| 凉城县| 四平市| 通海县| 调兵山市| 遂平县| 黔西| 梨树县| 鲜城| 龙口市| 七台河市|