This is a short introduction to the Scala language for those familiar with JavaScript ES6. We are comparingto ES6 instead of earlier versions of JavaScript because ES6 contains many nice features and syntax changes that bringit closer to Scala.
The best way to experiment with Scala is to use a Scala REPL, or the worksheetfunctionality in the ScalaIDE or IntelliJIDEA.
For more reading check out Scala Exercises, ScalaSchool and official Scala Tutorials.
The Scala language
Scala is a modern multi-paradigm programming language designed to express common programming patterns in a concise,elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages. Scala is apure object-oriented language in the sense that every value is an object. It is also a functional language in the sensethat every function is a value and that immutability is favored over mutability.
This combination of paradigms is not alien to JavaScript developers.JavaScript is also object-oriented, although primitive values are not considered as objects.It is at least partially functional as well, since functions are values and can be passedaround to other functions (such as Array.prototype.map
).However, although it is possible to write with an immutable mindset in JavaScript,the language does not encourage immutability.
The biggest difference to JavaScript is that Scala is statically typed. This means that it is equipped with anexpressive type system that enforces statically that abstractions are used in a safe and coherent manner, meaning thecompiler will catch many typical programming errors. If you have used other statically typed languages like Java or C#before you may have noticed that type definitions are all over the place. This is not true with Scala where the compilercan infer most of the types automatically.
Variables
Let’s start with something simple, variables. Both Scala and ES6 support mutable and immutable variables.
ES6
// mutable variable
let x = 5;
// immutable variable
const y = "Constant";
Scala
// mutable variable
var x = 5
// immutable variable
val y = "Constant"
Note that the Scala compiler automatically infers the types for x
and y
from the values that are assigned. In Scalaboth mutable and immutable variables must always be initialized when declared.
Primitive types
Scala defines several primitive types, of which most have corresponding types in JavaScript as well. The following table presents the most commonly used ones (there are also Byte
, Short
and Float
).
Scala type | JavaScript type | Notes |
---|---|---|
String | string | |
Boolean | boolean | |
Int | number | integer, range (-2147483648, 2147483647) |
Double | number | 64-bit floating point, fully equivalent to JS number |
Long | N/A | 64-bit integer |
Char | N/A | UTF-16 code unit |
Unit | undefined | |
Null | null |
In JavaScript all numbers are represented as 64-bit floating point internally, which may give surprising results whenmaking some calculations. In Scala calculations are always performed using the types of operands, so dividing an Int
with another Int
, the result is rounded to an Int
.
ES6
const x = 5 / 3; // == 1.6666666666666667
Scala
val x = 5 / 3 // == 1
val y = 5.0 / 3 // == 1.6666666666666667
val z = 5 / 3.0 // == 1.6666666666666667
Because in JavaScript every number is a number
there is no need to do type conversions. In Scala, however, it is anerror if you try to assign a higher precision value to a lower precision variable. You must explicitly convert it usingan appropriate function.
Scala
val x: Double = 3 // Ok!
val y: Int = 3.5 // Compile error
val z: Int = 3.5.toInt // Ok!
val a: Int = x // Compile error
val b: Int = x.toInt // Ok!
Functions
Defining functions is quite similar in both languages.You just replace the function
keyword with def
, and add types for theparameters and the result type.Speaking of which, this is about the only place you will explicitly write typesin Scala. The types of local values inside functions are usually inferred by thecompiler.Actually, even the result type will usually be inferred too, but it is goodpractice to explicitly define it, to help catch potential type errors.
Note that there is no need for a return
keyword: the last expression in thefunction is automatically used as the return value.
ES6
function mult(x, y) {
return x * y;
}
Scala
def mult(x: Double, y: Double): Double = x * y
Anonymous functions
In functional programming you quite often need to provide a function as a parameter, but you don’t need it elsewhere soit can be anonymous. Both languages support the nice “fat arrow” notation for defining anonymous functions conveniently.
ES6
const f = (x, y) => x + y;
const p = ["Fox", "jumped", "over", "me"];
const l = p.map(s => s.length)
.reduce((a, b) => a + b, 0); // == 15
Scala
val f = (x: Double, y: Double) => x + y
val p = Array("Fox", "jumped", "over", "me")
val l = p.map(s => s.length)
.foldLeft(0)((a, b) => a + b) // == 15
Default, named and rest parameters
You can also define default values for parameters if they are not supplied when the function is called. For variablenumber of parameters, you can access those as a Seq
(see thecollections part of this tour for more info).Named parameters work just as you would expect in Scala, whereasin ES6 you need to supply them with the object notation.
ES6
// default value
function mult(x, y = 42.0) {
return x * y;
}
// variable number of parameters
function sum(...args) {
return args.reduce((a, b) => a + b, 0);
}
const s = sum(5, 4, 3, 2, 1); // == 15
// named parameters
function vec({x = 0, y = 0, z = 0}) {
return new Vec(x, y, z);
}
const v = vec({x: 8, z: 42}); // Vec(8, 0, 42)
Scala
// default value
def mult(x: Double, y: Double = 42.0): Double =
x * y
// variable number of parameters
def sum(args: Double*): Double =
args.foldLeft(0.0)((a, b) => a + b)
val s = sum(5, 4, 3, 2, 1) // == 15
// named parameters (works directly)
def vec(x: Int = 0, y: Int = 0, z: Int = 0): Vec =
new Vec(x, y, z)
val v = vec(8, z = 42) // Vec(8, 0, 42)
Again, the Scala compiler can infer all the required types in the code above, including the parameters for the anonymousfunction given to the foldLeft
function.
if, while, for, match control structures
As you would expect, Scala has the regular if-else
and while
control structures found in most programminglanguages. The big difference to JavaScript is that if
statements are actually expressions returning a value. InJavaScript you have the special a ? b : c
construct to achieve the same result.
ES6
const res = (name === "") ? 0 : 1;
Scala
val res = if (name == "") 0 else 1
The for
construct in Scala is quite different from the for-loop in JavaScript and also much more powerful. You can useit to iterate over numerical ranges or collections in both languages:
ES6
let x = 0;
for (let i = 0; i < 100; i++)
x += i * i;
const p = ["Fox", "jumped", "over", "me"];
for (let s of p) {
console.log(`Word ${s}`);
}
Scala
var x = 0
for (i <- 0 until 100)
x += i * i
val p = Array("Fox", "jumped", "over", "me")
for (s <- p) {
println(s"Word $s")
}
In case you have nested for-loops, you can easily combine them into one for-comprehension in Scala. Inside the for
you can even filter using if
expressions. In Scala a for-comprehension is just syntactic sugar for a series offlatMap
, map
and withFilter
calls making it very handy when dealing with Scala collections.
ES6
function findPairs(n, sum) {
for (let i = 0; i < n; i++) {
for (let j = i; j < n; j++) {
if (i + j == sum)
console.log(`Found pair ${i}, ${j}`);
}
}
};
findPairs(20, 31);
Scala
def findPairs(n: Int, sum: Int): Unit = {
for {
i <- 0 until n
j <- i until n if i + j == sum
} println(s"Found pair $i, $j")
}
findPairs(20, 31)
The code above also serves as an example for string interpolation (in Scala) and template strings (in ES6). Bothmake it easier to construct strings using variables or function calls. In Scala you don’t need to enclose the variablein {}
if it’s just a simple variable name. For more complex cases you’ll need to use the s"Length = ${data.length}"
syntax.
Finally the match
construct provides pattern matching capabilities in Scala. Pattern matching is a complex topiccovered in more detail in the advanced section of this article, so here we just focus on the simple use cases likereplacing JavaScript switch
/case
with it.
ES6
const animal = "Dog";
let description;
switch(animal) {
case "Cat":
case "Lion":
case "Tiger":
description = "It's feline!";
break;
case "Dog":
case "Wolf":
description = "It's canine!";
break;
default:
description = "It's something else";
}
console.log(description);
Scala
val animal = "Dog"
val description = animal match {
case "Cat" | "Lion" | "Tiger" =>
"It's feline!"
case "Dog" | "Wolf" =>
"It's canine!"
case _ =>
"It's something else"
}
println(description)
In Scala you can use the |
-operator to match multiple choices and there is no need (nor support) for break
, as casesnever fall through like they do in JavaScript. For the default case, use the ubiquitous _
syntax (it has many manymore uses in Scala!) As with if
, a match
is an expression returning a value that you can directly assign to avariable.
Classes
Being an object-oriented language, Scala naturally supports classes with inheritance. In addition to basic classes Scalaalso has:
case class
es for conveniently storing dataobject
s for singletonstrait
s for defining interfaces and mixins
Let us look at a simple class hierarchy in both languages.
ES6
class Shape {
constructor(x, y) {
this.x = x;
this.y = y;
}
move(dx, dy) {
this.x += dx;
this.y += dy;
}
draw() {
console.log(`Shape at ${this.x}, ${this.y}`);
}
};
class Circle extends Shape {
constructor(x, y, r) {
super(x, y);
this.r = r;
}
draw() {
console.log(`Circle at ${this.x}, ${this.y} with radius ${this.r}`);
}
}
const c = new Circle(5, 5, 42);
const r = c.r; // == 42
Scala
// use var to make coordinates mutable
abstract class Shape(var x: Int, var y: Int) {
def move(dx: Int, dy: Int): Unit = {
x += dx
y += dy
}
def draw(): Unit = {
println(s"Shape at $x, $y")
}
}
// r is immutable but accessible outside the class
class Circle(x: Int, y: Int, val r: Int)
extends Shape(x, y) {
override def draw(): Unit = {
println(s"Circle at $x, $y with radius $r")
}
}
val c = new Circle(5, 5, 42)
val r = c.r // == 42
Note that this
is typically omitted in Scala, since the compiler can tell thatx
, y
and r
are properties of the enclosing class (and not local variables).
Case classes
Case classes are a particular kind of class in Scala which have a lot ofcompiler-generated goodies. They are particularly suited for immutable datacontainers whose instances are equal if and only if their fields are pairwiseequal. They also automatically receive a sensible toString()
representation,and they can be instantiated without the new
keyword.
JavaScript doesn’t quite have a similar construct, but whenever you would usethe regular object notation, consider using a case class instead.
ES6
const person = {first: "James", last: "Bond"};
Scala
case class Person(first: String, last: String)
val person = Person("James", "Bond")
Case classes enforce type safety and prevent constructing invalid objects with missing fields.
The Scala compiler automatically generates a proper equals
method for case classes, making comparing them trivial. In ES6you would typically go for a library like lodash to avoid writing the complexcomparison code yourself.
ES6
const o1 = {a: 1, x: "test"};
const o2 = {a: 1, x: "test"};
if (o1 != o2) {
// this doesn't work as expected
console.log("They are not equal!");
}
if (_.isEqual(o1, o2)) {
console.log("They are equal!");
}
Scala
case class AX(a: Int, x: String)
val o1 = AX(1, "test")
val o2 = AX(1, "test")
if (o1 == o2) {
println("They are equal!")
}
Fields in case classes are public and immutable by default (unless you define them with var
modifier) so you cannot make changesto instances. Instead of modifying the instance you make a copy and modify one or more fields during the copy. Scalaprovides a suitable copy
function for each case class automatically. In ES6 you can use Object.assign
to achieve thesame result.
ES6
const o1 = {a: 1, x: "test"};
// start with empty object to prevent
// modification of o1
const o2 = Object.assign({}, o1, {a: 42});
Scala
case class AX(a: Int, x: String)
val o1 = AX(1, "test")
val o2 = o1.copy(a = 42)
Finally case classes can be used nicely in pattern matching, which is covered in the advanced section.
Objects
An object
is a special class with only a single instance: a singleton. JavaScript also has a singleton design pattern(or actually several) even though the language itself does not have direct support for the concept. Singletons areuseful for putting stuff in a shared namespace without polluting the global scope.
ES6
const RandomGen = {
_privateMethod() {
console.log("I am private");
},
_rnd() {
return Math.random()
},
publicMethod() {
console.log("The public can see me!");
this._privateMethod();
},
name: "RandomGen",
getRandomNumber() {
return this._rnd()
}
}
const r = RandomGen.getRandomNumber();
Scala
import scala.util.Random
object RandomGen {
private def privateMethod(): Unit = {
println("I am private")
}
private val rnd = new Random()
def publicMethod(): Unit = {
println("The public can see me!")
privateMethod()
}
val name = "RandomGen"
def getRandomNumber: Double = rnd.nextDouble()
}
val r = RandomGen.getRandomNumber
As you can see, defining singleton objects in Scala is quite trivial thanks to the native support in the language.
Another common use for object
s in Scala is using them as companion objects for classes to store static variablesand methods shared by all instances of the class.
Traits
Scala trait
s are similar to the mixin design pattern in JavaScript by allowing developer to define behaviors for classcomposition. Because of Scala’s strict type system, traits are commonly used to describe common interfaces for a groupof implementation classes. JavaScript itself has no need for interfaces, but some extensions like TypeScript supportthem for the same purpose as Scala.
ES6
class Circle extends Shape {
constructor(x, y, r) {
super(x, y);
this.r = r;
}
draw() {
console.log(`Circle at ${this.x}, ${this.y} with radius ${this.r}`);
}
}
const Clickable = {
onClick() {
console.log("Clicked!");
}
};
class ClickableCircle extends Circle {}
Object.assign(ClickableCircle.prototype, Clickable);
const cc = new ClickableCircle(0, 0, 42);
cc.onClick();
Scala
class Circle(x: Int, y: Int, val r: Int)
extends Shape(x, y) {
override def draw(): Unit = {
println(s"Circle at $x, $y with radius $r")
}
}
trait Clickable {
def onClick(): Unit = {
println("Clicked!")
}
}
class ClickableCircle(x: Int, y: Int, r: Int)
extends Circle(x, y, r) with Clickable
val cc = new ClickableCircle(0, 0, 42)
cc.onClick()
Note that there are many ways for defining mixins in JavaScript, using Object.assign
is just one of them supported byES6.
Option, the type safe undefined
The notorious undefined
type in JavaScript can be a blessing or a curse. On the other hand it makes life easy byallowing you to drop function parameters or leave variables undefined. But then it also masks many errors and makesyou write extra code to check for undefined
. Quite often undefined
is used to make a distinction between anexisting value (of any type) and a missing value.
Scala doesn’t have undefined
(it does have null
but its use is discouraged), but instead it has anOption
trait for representing optional values. In Scala.js the undefined
type exists to supportinteroperability with JS libraries, but even there it is recommended to use Option
whenever possible.
Option[A]
is a container for an optional value of type A
(note that Option[A]
is Scala’s notation for type parameters, which mostprogramming languages, including TypeScript, write as Option<A>
).If the value of type A
is present, the Option[A]
is an instance of Some[A]
,containing the present value of type A
. If the value is absent, the Option[A]
is the object None
.
ES6
function log(msg, context) {
let s;
if (context !== undefined)
s = `[${context}] ${msg}`;
else
s = msg;
console.log(s);
};
// produces: First message
log("First message");
// produces: [debug] Second message
log("Second message", "debug");
Scala
def log(msg: String,
context: Option[String] = None): Unit = {
val s = context match {
case Some(c) => s"[$c] $msg"
case None => msg
}
println(s)
}
log("First message")
log("Second message", Some("debug"))
Pattern matching works nicely with Option
, but there are more powerful ways to use it. Let’s rewrite the previousfunction another way giving us the same result.
Scala
def log(msg: String, context: Option[String] = None): Unit = {
val s = context.map(c => s"[$c] $msg").getOrElse(msg)
println(s)
}
Whoa, quite a reduction in code size! Next let’s see how we can process a sequence of option values.
ES6
const data = [1, 2, 3, undefined, 5, undefined, 7];
const res = data.filter((x) => x !== undefined);
Scala
val data = Array(Some(1), Some(2), Some(3),
None, Some(5), None, Some(7))
val res = data.filter(x => x.isDefined)
Option
provides many collection like methods like map
, filter
and flatMap
, which are discussed in the nextchapter.