与Java内部类相比,Scala闭包 - >最终VS变量 [英] Scala closures compared to Java innerclasses -> final VS var

查看:105
本文介绍了与Java内部类相比,Scala闭包 - >最终VS变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次询问关于在Java中使用匿名内部类的 final 的问题:
为什么我们使用final关键字和匿名内部类?



我实际上正在阅读Martin Odersky的Scala书。看起来Scala简化了很多Java代码,但对于Scala闭包,我可以注意到一个显着的区别。在Java中,我们使用匿名内部类模拟闭包,捕获一个最终变量(将被复制到堆而不是堆栈),在Scala中,我们可以创建一个闭包,它可以捕获一个val,但也是一个var,从而更新它在闭包调用! / p>

所以这就像我们可以使用一个没有 final 关键字的Java匿名内部类。
我没有读完这本书,但是现在我没有找到足够的关于这种语言设计选择的信息。



有人可以告诉我为什么Martin Odersky,真的似乎在照顾功能的副作用,选择闭包能够捕获 val var ,而不是只有 val



Java和Scala实现的好处和缺点是什么?



感谢




使用Scala闭包时,捕获的变量何时开始在JVM堆上生效?看到一袋封闭,共享访问相同的环境,这种环境通常是可变的。那么,为什么使从匿名函数生成的闭包更为强大呢?



另外,其他具有可变变量和匿名函数的语言的工作方式相同。租赁惊讶原则。 Java实际上是WEIRD,不允许可变变量被内部类捕获。



有时它们只是有用。例如,一个自我修改的thunk来创建自己的惰性或未来处理的变体。



缺点?他们有共享的可变状态的所有缺点。


I've first asked this question about the use of final with anonymous inner classes in Java: Why do we use final keyword with anonymous inner classes?

I'm actually reading the Scala book of Martin Odersky. It seems Scala simplifies a lot of Java code, but for Scala closures I could notice a significant difference.

While in Java we "simulate" closures with an anonymous inner class, capturing a final variable (which will be copied to live on the heap instead of the stack) , it seems in Scala we can create a closure which can capture a val, but also a var, and thus update it in the closure call!

So it is like we can use a Java anonymous innerclass without the final keyword! I've not finished reading the book, but for now i didn't find enough information on this language design choice.

Can someone tell me why Martin Odersky, who really seems to take care of function's side effects, choose closures to be able to capture both val and var, instead of only val?

What are the benefits and drawbacks of Java and Scala implementations?

Thanks

Related question: With Scala closures, when do captured variables start to live on the JVM heap?

解决方案

An object can be seen a bag of closures that share access to the same environment and that environment is usually mutable. So why make closures generated from anonymous functions less powerful?

Also, other languages with mutable variables and anonymous functions work the same way. Principle of lease astonishment. Java is actually WEIRD in not allowing mutable variables to be captured by inner classes.

And sometimes they're just darn useful. For example a self modifying thunk to create your own variant of lazy or future processing.

Downsides? They have all the downsides of shared mutable state.

这篇关于与Java内部类相比,Scala闭包 - >最终VS变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆