Scala vs Java

From Glitchdata
Jump to navigation Jump to search


Here is a simple Java example:

public final class Person implements Serializable {
    public final String name;
    public final String surname;
    public Person(String name, String surname) {
        if (name == null) throw new IllegalArgumentException("Null name");
        if (surname == null) throw new IllegalArgumentException("Null surname");
        this.name = name;
        this.surname = surname;
    }
    public String toString() {
        return String.format("Person(%s, %s)", this.name, this.surname);
    }
    public boolean equals(Object o) {
        if (o == null || !(o instanceof Person)) return false;
        Person p = (Person)o;
        return (this.name.equals(p.name)) && (this.surname.equals(p.surname));
    }
    public int hashCode() {
        return 31 * name.hashCode() + surname.hashCode();
    }
}

And a similar Scala version:

case class Person(name: String, surname: String)

The point here is, you just need to define what a class is and what its "parameters" (members) are. Common boilerplate code is often unnecessary, the main example being setters and getters methods. You can substitute these unnecessary constructions with underlying code generated by the compiler, thus raising the level of abstraction and simplicity a language can attain.

Don't get me wrong, Java is a good language. It introduced a better level of abstraction compared to previous languages. But it does have issues with the amount of code necessary to express a solution.

As Java's father himself said [1], the main innovation wasn't the language but the platform that became possible with the advent of the first de facto virtual machine.


About the statement tha Java "introduced a better level of abstraction compared to previous languages". I was talking about C and C++, the two main languages used at that time (and still strong today). Simula 67 introduced classes and objects and predates C, but didn't became mainstream (even its conceptual offspring weren't that strong). It is like Java was designed to teach and enforce better programming. After that, the side effect is it gets in the way of pratical programming. Sure IDEs help you, but you shouldn't need that. They fix some of the problems you shouldn't have (because of a flawed design).

Benefits

I think Scala is the best alternative to Java:

  • It compiles to the Java's virtual machine;
  • You can use Java libraries;
  • Type safety is a #1 concern;
  • Adds functional programming ;
  • It has a strong community and adoption;
  • Directly related to the question here, it isn't verbose at all;
  • Java, despite being updated to get better, won't rethink itself so much. There's too much legacy. Too much momentum to turn such a big cargo ship so fast;

Links