- 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.
- Rust實(shí)戰(zhàn)
- FFmpeg入門詳解:音視頻流媒體播放器原理及應(yīng)用
- Web程序設(shè)計(jì)(第二版)
- 網(wǎng)站構(gòu)建技術(shù)
- H5頁(yè)面設(shè)計(jì):Mugeda版(微課版)
- UNIX Linux程序設(shè)計(jì)教程
- 軟件測(cè)試綜合技術(shù)
- RESTful Web Clients:基于超媒體的可復(fù)用客戶端
- Python函數(shù)式編程(第2版)
- Vue.js 3應(yīng)用開發(fā)與核心源碼解析
- 零基礎(chǔ)輕松學(xué)C++:青少年趣味編程(全彩版)
- Learning Android Application Testing
- 零基礎(chǔ)學(xué)C++(升級(jí)版)
- Mastering Drupal 8
- 體驗(yàn)之道:從需求到實(shí)踐的用戶體驗(yàn)實(shí)戰(zhàn)