在迁移到Scala时,应对Java形成的习惯 [英] Struggle against habits formed by Java when migrating to Scala

查看:166
本文介绍了在迁移到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形成的习惯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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