从Scala到Java来回

两年多来,我几乎只在后端的Scala中编程,而前端则主要使用JavaScript和TypeScript。 在此之前,我主要使用Java超过15年,还有其他几种编程语言 一个月以来,我在一次作业中使用Java,甚至使用Java 8,我以为我分享了自己的经验。 之所以再次使用Java,是因为客户端广泛地使用Java,我想知道如果需要的话,切换回去有多么容易。 毕竟我声称自己与编程语言无关

首先,回去并没有我想的那么难,所有这些很快就回到了我身边。 当然,我需要添加; 和一些多余的代码,但这是可行的。

Lambda's

我使用Java 8,这是第一个具有lambda的Java版本。 我不认为我不能忍受一门语言。 我使用lambda的程度很高,可能比从未使用过编程语言的人更多。 Scala用途=>,Java用途->,但是没关系。

Mutable data

Just as in Scala, mutable data-structures can lead to unpredictable behavior. In the Scala world people are by now pretty used to using immutable data-structures.
In the Java world, rather then thinking about how to transform data correctly, people still deliberate about anthropomorphic questions like what responsibilities an object has and how a Employee class relates to an employee in the real world.

Option

Java 8 introduced the Optional class, so there's no excuse for having NullPointerExceptions in your code (well, except when using older code and libraries).
Java 8 Optional has a map method. Annoyingly, it's orElse method of Option returns the actual value type instead of the value wrapped in an Optional, so you can't chain an orElse. I have no idea what the language designers were thinking. Well, as alternative I could use map, but that's a bit less readable:

      Optional<String>  firstName=Optional.of("John");
      Optional<String>  lastName=Optional.empty();
      Optional<String> name = firstName.map(Optional::of).orElse(lastName);

Fortunately, Java 9 introduced or.

Optional and streams

Also, Java's Optional can't be used as Iterable, while Scala's Option can. Allowing to treat Option as a collection of zero or one values helped me better understanding what an Option is and how you could use it beyond the isPresent() method.
Converting an Option to a Stream shouldn't be too hard:

    public static <T> Stream<T> stream(Optional<T> option) {
        return option.map(Stream::of).orElse(Stream.empty());
    }

然后,我可以这样写:

      Optional<String>  firstName=Optional.of("John");
      Optional<String> middleName=Optional.empty();
      Optional<String>  lastName=Optional.of("Doe");

      ...
   private String toName(Optional<String> firstName, Optional<String> middleName, Optional<String> lastName) {
      return Stream.of(
              stream(firstName),
              stream(middleName),
              stream(lastName))
              .flatMap(Function.identity())
              .collect(Collectors.joining(" "));
   }

这看起来不再那么简洁,但可以说比嵌套块更好。

Try catch finally and Either

In Java 8, when you use a resource that implements the Closeable interface working, a finally block to close the resource is no longer necessary. That's pretty nice:

    public String readMe() throws IOException {
        try(BufferedReader in = new BufferedReader(new FileReader("some file.txt"))) {
            return in.readLine();
        }
    }

At least when an exception is thrown, the resource is closed. What I greatly miss, is a Try class, Either or something similar so no exception is thrown by the method at all. There are a few libraries that do add something like Either, like functionalj, but of course these are non-standard so a bit harder to introduce at project.

Beyond the limits of imperative OO: annotations, aspects and reflection.

As is pretty common, Spring is also used to extend Java. Spring is based on the principle of aspect- or plugin-oriented programming and heavily relies on bytecode-enhancement and reflection to extend the language Java. In practice this means you use either annotations or config files.
The biggest disadvantage: everything is applied at runtime, e.g., when your application runs.
In Scala, the language itself is flexible enough using pattern matching, implicits, macros and other language constructs.
Scala pattern matching does use reflection in some cases, but most errors are catched compile time rather then runtime. And despite people complaining about implicit, having an error during compilation because you forgot to import an implicit is a lot easier to handle than an error that occurs when running your software because some configuration is wrong, or something fails during reflection.

当错误地使用注释时,Spring会给您带来非常好的错误,并且IntelliJ确实对Spring提供了良好的支持。 因此,在大多数情况下,您会收到有关缺少的bean,错误的spring-configuration等的合理描述性警告或错误,这使Spring几乎感觉成为该语言的一部分。 而且,即使仅仅是因为您的代码中充斥着注释,它仍然让人感到麻烦。

Lombok, case classes

Scala introduced case classes, which allows you to write value based classes without a lot of boilerplate - or mistakes like accidentally committing a property in equals or hashCode.

Java by default doesn't. I'm very glad someone created Lombok and it seems well accepted.

import lombok.Value;

@Value
public class Employee {
    String firstName;
    String middleName;
    String lastName;
    long employNumber;
}

您无法完成在Scala中可以做的所有事情,例如在案例类上进行模式匹配,并且与Scala不同,Java中的方法和属性之间仍然存在差异。 但这要比生成equals,toString和get'ter方法好得多。

一世DE support for Lombok is very good, so you hardly notice you're using language extensions.

Conclusion

从Scala到Java来回切换是可行的,但我当然不希望无限期地返回。 Scala世界仍在蓬勃发展。 Java是可以接受的,但是Scala使编程成为可能。

from: https://dev.to//gerbrandvd/back-and-forth-from-scala-to-java-ah9

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值