您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

一个明显的例子是不利用scala允许的嵌套作用域,以及延迟副作用(或意识到scala中的所有内容都是表达式):

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"))
}

但这可以在很多方面得到改善。它可能是:

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")
}

一个示例不会“导出”超出所需范围的任何变量。事实上,它不声明任何变量 在所有 。这意味着以后更容易重构。当然,这种方法 的确 导致了类文件的巨大膨胀!

java 2022/1/1 18:37:17 有364人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶