使用外部函数中的变量是一种好习惯吗?
Is it good practice to use variables from outer functions?
我尝试学习 Scala 编程语言。
在内部函数中从外部函数使用 variables/arguments 是好的和流行的做法吗?
例如:
def foo(x: Int) = {
val x2 = 10
def foo2()
{
// is it normal to use x and x2 here?
}
}
是的,在 Scala 中称为 闭包。如果 x
一个 x2
出现在 foo2
的范围内,您必须关闭提供两个变量值的开放项 (foo2
)。
您可以访问在 foo2
之外定义的变量,因此在您的内部函数范围内显示为自由变量。例如,请考虑:
// some context
val more: Int = 4
def sumMore(x: Int): Int = x + more
在最后一行,我们有 x
这是一个绑定变量,more
作为一个自由变量出现在 sumMore
函数中。
任何具有自由变量的函数文字(如 sumMore
,取决于 more
的值)将是一个开放式术语,因为它需要绑定 more
。名称 closure 源于通过为出现在其主体范围内的自由变量提供值来关闭开放项的行为。
让我们看看如果我们不为 more
提供值会发生什么:
scala> def sumMore(x: Int): Int = x + more
<console>:7: error: not found: value more
def sumMore(x: Int): Int = x + more
^
如果more
在sumMore
的范围内(定义在外面):
scala> val more: Int = 4
more: Int = 4
scala> def sumMore(x: Int): Int = x + more
sumMore: (x: Int)Int
我尝试学习 Scala 编程语言。
在内部函数中从外部函数使用 variables/arguments 是好的和流行的做法吗?
例如:
def foo(x: Int) = {
val x2 = 10
def foo2()
{
// is it normal to use x and x2 here?
}
}
是的,在 Scala 中称为 闭包。如果 x
一个 x2
出现在 foo2
的范围内,您必须关闭提供两个变量值的开放项 (foo2
)。
您可以访问在 foo2
之外定义的变量,因此在您的内部函数范围内显示为自由变量。例如,请考虑:
// some context
val more: Int = 4
def sumMore(x: Int): Int = x + more
在最后一行,我们有 x
这是一个绑定变量,more
作为一个自由变量出现在 sumMore
函数中。
任何具有自由变量的函数文字(如 sumMore
,取决于 more
的值)将是一个开放式术语,因为它需要绑定 more
。名称 closure 源于通过为出现在其主体范围内的自由变量提供值来关闭开放项的行为。
让我们看看如果我们不为 more
提供值会发生什么:
scala> def sumMore(x: Int): Int = x + more
<console>:7: error: not found: value more
def sumMore(x: Int): Int = x + more
^
如果more
在sumMore
的范围内(定义在外面):
scala> val more: Int = 4
more: Int = 4
scala> def sumMore(x: Int): Int = x + more
sumMore: (x: Int)Int