There are other such tutorials, but I find that they don't hurl enough angry insults at Java. So I'm writing one that contains a sufficient amount of fury. We're going to introduce Scala concepts alongside their fucking stupid Java counterparts.
Scala
Java
The two languages don't differ here. An empty file is valid and produces no bytecode.
Scala
package foo
class Foo
Java
package foo;
public class Foo {}
Everything in Scala has a sane default access control of public
. Java's default (the rather obscurely-named package-private) is almost never what you want, so Java is littered with public
and private
modifiers on every damn thing. Your Scala code will contain significantly fewer access control modifiers.
Java requires these fucking braces {}
even though there's nothing in them. The syntax is the same in Scala, but Scala isn't interested in making you do that shit when the block is goddamn empty.
And, of course, the Java snippet has that inane semicolon.
Scala
class Foo
class Bar
Java
Fuck you.
Actually, a Java file can contain multiple top-level classes, but at most one of them may be public
. Any others must be package-private. God knows why.
Java
public class Foo {}
class Bar {}
Scala
package a { class Foo }
package b { class Bar }
Java
No fucking way.
You don't often write shit like this because you're not an asshat, but sometimes package nesting comes in handy:
Scala
package a.b
class Foo // a.b.Foo
package c.d {
class Foo // a.b.c.d.Foo
package e {
class Foo // a.b.c.d.e.Foo
}
}
package f {
class Foo // a.b.f.Foo
}
Scala
var x = "a"
Java
String x = "a";
Here we introduce type inference, also known as "stop specifying shit that the computer can figure out on its own".
Scala
val x = "a"
Java
final String x = "a";
Java forces you to make a terrible choice: Use mutable references, or suffer the syntactic vinegar final
.
Scala
object Foo {
val x = "a"
}
Java
public final class Foo {
public static final Foo INSTANCE = new Foo();
private Foo() { }
public final String x = "a";
}
or
public final class Foo {
public static final String x = "a";
}
No longer do you have to use "the singleton pattern". That shit's built-in, and you use it by writing object
instead of class
.
Unlike weak-ass Java static "util class" methods, a Scala object
's methods can implement interface methods.