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

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

问题描述

我首先问了这个关于在 Java 中将 final 与匿名内部类一起使用的问题:为什么我们对匿名内部类使用 final 关键字?

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?

我实际上正在阅读 Martin Odersky 的 Scala 书.Scala 似乎简化了很多 Java 代码,但对于 Scala 闭包,我可以注意到显着差异.

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.

虽然在 Java 中我们用匿名内部类模拟"闭包,捕获最终变量(它将被复制到堆上而不是堆栈上),但在 Scala 中似乎我们可以创建一个可以捕获一个闭包的闭包val,但也是一个 var,因此在闭包调用中更新它!

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!

所以这就像我们可以使用没有 final 关键字的 Java 匿名内部类!我还没有读完这本书,但目前我没有找到关于这种语言设计选择的足够信息.

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.

谁能告诉我为什么 Martin Odersky,他似乎真的很关心函数的副作用,选择闭包来同时捕获 valvar,而不是只有val?

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?

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

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

谢谢

相关问题:使用 Scala 闭包,捕获的变量什么时候开始存在于 JVM 堆中?

推荐答案

一个对象可以被看作是一包闭包,它们共享对同一环境的访问,而该环境通常是可变的.那么为什么要让匿名函数生成的闭包变得不那么强大呢?

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?

此外,其他具有可变变量和匿名函数的语言也以同样的方式工作.租赁惊奇原则.Java 实际上很奇怪,它不允许内部类捕获可变变量.

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.

有时它们非常有用.例如,一个自我修改的 thunk 来创建你自己的懒惰或未来处理的变体.

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.

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

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