Skip to content

Instantly share code, notes, and snippets.

@michalrus
Last active December 19, 2015 01:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michalrus/5875993 to your computer and use it in GitHub Desktop.
Save michalrus/5875993 to your computer and use it in GitHub Desktop.
Scala *only* as "Java without semicolons". Let's take a look. Equivalent Java-Scala pairs are presented below.
// Let's say we want to create an immutable Point class
public class Point {
public final double x;
public final double y;
public Point(final double x, final double y) {
this.x = x;
this.y = y;
}
}
// Now, the same exact code in Scala:
class Point(x: Double, y: Double)
// But what if we wanted to be able to to create (0,0) by default?
public class Point {
public final double x;
public final double y;
public Point() {
this(0, 0);
}
public Point(final double x, final double y) {
this.x = x;
this.y = y;
}
}
// ;)
class Point(x: Double = 0, y: Double = 0)
// Let's do something more serious: translation to polar coordinates!
public class Point {
public final double x;
public final double y;
public Point(final double x, final double y) {
this.x = x;
this.y = y;
}
public double r() {
return Math.sqrt(x * x + y * y);
}
public double phi() {
return Math.atan2(y, x);
}
}
// Equivalent code which you could even call from your Java code!
import scala.math
class Point(x: Double, y: Double) {
// Everything is public by default
def r = math.sqrt(x * x + y * y)
// Notice how we don't need to specify return types because the
// compiler is able to guess them (still it's static typing!)
def phi = math.atan2(y, x)
}
// And if we wanted a .toString() method?
public class Point {
public final double x;
public final double y;
public Point(final double x, final double y) {
this.x = x;
this.y = y;
}
public String toString() {
return "Point(" + x + "," + y + ")";
}
}
// It's enough to add "case" before "class", to get a default
// .toString output of which looks like in above Java example:
// "CaseClassName(param1,param2,...)"
case class Point(x: Double, y: Double)
// (When using case classes we get some other advantages, as well.)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment