开发者

What is a full powered closure?

开发者 https://www.devze.com 2023-01-07 12:58 出处:网络
I was at a Java conference on Scala the other day and the speaker referred to \'full powered closures\'.I am having a hard time nailing down a definition tha开发者_Go百科t makes sense to me.I have rea

I was at a Java conference on Scala the other day and the speaker referred to 'full powered closures'. I am having a hard time nailing down a definition tha开发者_Go百科t makes sense to me. I have read the wiki page on closures but it really didn't answer it for me. Can someone help me with a clear cut definition? Maybe even include a simple example.

Thanks!


In computer science, a closure is a first-class function with free variables that are bound in the lexical environment.

You don't need more than this sentence from the wikipedia article. What Java lacks (in addition to the ugly syntax) is the feature of binding free variables from outside the closure. An example:

int x = 0;
new Runnable() {
    public void run() {
        x = 1;
    }
}.run();

Here the Java compiler will complain about the variable x.

The same thing in scala works just fine and is a lot less verbose:

var x = 0
val fun = ()=>{x=1}
fun


Since I feel like a beginner (compared to DPP and Amber) I might explain it to a beginner in a beginners language:

First, anonymous function (or code block/lambda expression) is simply a function that does not have a name. It could be tied to a variable like this.

scala> val foo = (x: Int) => 2*x 
foo: (Int) => Int = <function1>

scala> val bar = foo
bar: (Int) => Int = <function1>

scala> bar(5)
res2: Int = 10

You see, the function doesn't have the name foo, it could be called from bar instead.

Second, a closure is an anonymous function that has a variable that is not defined inside the function (the variable/value must have been declared before the function is defined). The term "full powered closure" might refer to this functionality.

scala> var constant = 7
constant: Int = 7

scala> val foo = (x: Int) => 2*x + constant
foo: (Int) => Int = <function1>

scala> foo(5)
res3: Int = 17

scala> constant = 6
constant: Int = 6

scala> foo(5)
res4: Int = 16

First time you see this, you might wonder what it is good for. In short, it has many sectors of application :-)


It's possible that the speaker used 'full powered' to mean the opposite of 'closure-like', which is what many languages actually have.


As far as I know, full powered closures doesn't mean anything in particular but it may mean: simplicity of syntax. There is a world of difference between newing up an anonymous inner class in Java vs. using something like (a => a < max). Perhaps the ability to form closures on all surrounding variables not just final ones.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号