Struggle against habits formed by Java when migrating to Scala(在迁移到 Scala 时与 Java 形成的习惯作斗争)
问题描述
Java 开发人员在迁移到 Scala 时最常犯的错误是什么?
What are the most common mistakes that Java developers make when migrating to Scala?
我所说的错误是指编写不符合 Scala 精神的代码,例如在类似 map 的函数更合适时使用循环,过度使用异常等.
By mistakes I mean writing a code that does not conform to Scala spirit, for example using loops when map-like functions are more appropriate, excessive use of exceptions etc.
另外一个是使用自己的 getter/setter,而不是由 Scala 生成的方法
one more is using own getters/setters instead of methods kindly generated by Scala
推荐答案
一个明显的问题是不要利用 scala 允许的嵌套作用域,以及副作用的延迟(或意识到 scala 中的所有内容都是一个表达式):
One obvious one is to not take advantage of the nested scoping that scala allows, plus the delaying of side-effects (or realising that everything in scala is an expression):
public InputStream foo(int i) {
final String s = String.valueOf(i);
boolean b = s.length() > 3;
File dir;
if (b) {
dir = new File("C:/tmp");
} else {
dir = new File("/tmp");
}
if (!dir.exists()) dir.mkdirs();
return new FileInputStream(new File(dir, "hello.txt"));
}
可以转换为:
def foo(i : Int) : InputStream = {
val s = i.toString
val b = s.length > 3
val dir =
if (b) {
new File("C:/tmp")
} else {
new File("/tmp")
}
if (!dir.exists) dir.mkdirs()
new FileInputStream(new File(dir, "hello.txt"))
}
但这可以改进很多.可能是:
But this can be improved upon a lot. It could be:
def foo(i : Int) = {
def dir = {
def ensuring(d : File) = { if (!d.exists) require(d.mkdirs); d }
def b = {
def s = i.toString
s.length > 3
}
ensuring(new File(if (b) "C:/tmp" else "/tmp"));
}
new FileInputStream(dir, "hello.txt")
}
后一个示例不会导出"超出所需范围的任何变量.事实上,它根本没有声明任何变量.这意味着以后更容易重构.当然,这种方法确实会导致类文件非常臃肿!
The latter example does not "export" any variable beyond the scope which it is needed. In fact, it does not declare any variables at all. This means it is easier to refactor later. Of course, this approach does lead to hugely bloated class files!
这篇关于在迁移到 Scala 时与 Java 形成的习惯作斗争的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在迁移到 Scala 时与 Java 形成的习惯作斗争


- Eclipse 的最佳 XML 编辑器 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 获取数字的最后一位 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 转换 ldap 日期 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01