在迁移到 Scala 时与 Java 形成的习惯作斗争

Struggle against habits formed by Java when migrating to Scala(在迁移到 Scala 时与 Java 形成的习惯作斗争)

本文介绍了在迁移到 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 形成的习惯作斗争

基础教程推荐