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 形成的习惯作斗争
基础教程推荐
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01