How do you define an anonymous function in lambda calculus terms (or how can I say some language supports anonymous functions)?

后端 未结 2 458
轮回少年
轮回少年 2021-02-09 13:55

Does java support in current version of 6 lambda expressions or \"anonymous functions\"? Is there something I can\'t do in java that I couldn\'t do with a programming language s

2条回答
  •  迷失自我
    2021-02-09 14:36

    One important distinction between (say) lambda expressions in C# and anonymous inner classes in Java is that in Java, any local variables referred to in the inner classes are captured by value - which is why the variable has to be final. That variable's value is copied into the inner class on construction.

    In C#, the variable can be changed by either the lambda expression or other code in the method, and those changes will be seen in both places too.

    You can emulate this in Java by wrapping the original variable in a mutable wrapper - e.g. a single element array - and making the wrapper variable final. It's a pretty grotty hack though.

    The biggest problem with using anonymous inner classes IMO is the sheer verbosity - stating the class you're extending, then the method you're overriding etc.

    For more on closures, and particularly comparing Java and C# in this respect, see my article on the topic.

提交回复
热议问题