简体   繁体   中英

Is it good practice to use variables from outer functions?

I try to learn Scala programming language.

Is it good and popular practice to use variables/arguments from outer function in inner function?

For example:

def foo(x: Int) = {
     val x2 = 10
     def foo2()
     {
         // is it normal to use x and x2 here?
     }
}

Yes, in Scala that's called closures . If x an x2 appear free in the scope of foo2 , you have to close that open term ( foo2 ) providing the values for both variables.

You can have access to variables defined outside foo2 and thus, appearing as free variables in the scope of your inner function. As an example, consider:

// some context
val more: Int = 4
def sumMore(x: Int): Int = x + more

In the last line, we have x which is a bound variable, and more which appears as a free variable inside the sumMore function.

Any function literal having free variables (like sumMore , which depends on the value of more ) will be an open term because it requires a binding for more . The name closure arises from the act of closing the open term by providing values to the free variables which appear in the scope of its body.

Let's see what happens if we do not provide a value for more :

scala> def sumMore(x: Int): Int = x + more
<console>:7: error: not found: value more
       def sumMore(x: Int): Int = x + more
                                      ^

What if more is in the scope of sumMore (defined outside):

scala> val more: Int = 4
more: Int = 4

scala> def sumMore(x: Int): Int = x + more
sumMore: (x: Int)Int

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM