- 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.
- Java面向?qū)ο筌浖_(kāi)發(fā)
- Oracle從新手到高手
- MySQL數(shù)據(jù)庫(kù)基礎(chǔ)實(shí)例教程(微課版)
- Oracle從入門(mén)到精通(第5版)
- ANSYS Fluent 二次開(kāi)發(fā)指南
- Android Wear Projects
- OpenGL Data Visualization Cookbook
- 小程序,巧應(yīng)用:微信小程序開(kāi)發(fā)實(shí)戰(zhàn)(第2版)
- Python 3快速入門(mén)與實(shí)戰(zhàn)
- C/C++代碼調(diào)試的藝術(shù)
- 川哥教你Spring Boot 2實(shí)戰(zhàn)
- HTML 5與CSS 3權(quán)威指南(第4版·上冊(cè))
- C#網(wǎng)絡(luò)程序開(kāi)發(fā)(第二版)
- 企業(yè)應(yīng)用架構(gòu)模式
- 企業(yè)級(jí)DevOps技術(shù)與工具實(shí)戰(zhàn)