简体   繁体   中英

How does Closures work in Scala?

I understood that closure is a function whose return value depends on the data defined on its outer function. In javascript, we can send parameters to inner functions like this

    add(x) {
       return addplus(y) {
                let z = this.x + y ;
                return z;
              }
    }
   var op = add(10)(20);

Does closures in scala too resemble javascript closures? Is it too valid to send parameters to inner functions in scala?

A closure is a function that captures the outer scopes in which it is defined, and therefore has access to entities defined outside its own scope.

One possible use of closure is the one you described, although the technique that leverages it (as mentioned in a comment) is called currying , that is modeling a function with n arguments as one with one argument that returns a function that takes n - 1 arguments.

You can port your Javascript code line by line in Scala:

def add(x: Int): Int => Int =
  y => x + y

Also, note that Scala has native support for currying:

def add(x: Int)(y: Int): Int =
  x + y

The two are semantically equivalent and by partially applying either of them you get a function that returns a function that sums x to its parameter. It can also be applied completely.

val following: Int => Int = add(1)
val two = following(1)
val three = following(two)
val four = add(two)(two)

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