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 形成的习惯作斗争


基础教程推荐
- 多个组件的复杂布局 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java Swing计时器未清除 2022-01-01