The following set of sections provides a quick tutorial on the Scala language.
The target audience is people who already have some experience of programming and who are familiar with the JVM.
Programming languages give programmers ways to express computations.
Every non-trivial programming language provides:
Here are some examples of primitive expressions:
(Note the usage of double quotes,
More complex expressions can be expressed by combining simpler expressions using operators. They can therefore express more complex computations:
1 + 2
"Hello, " ++ "Scala!"
A non-primitive expression is evaluated as follows.
The evaluation process stops once it results in a value.
Here is the evaluation of an arithmetic expression:
(1 + 2) * 3 3 * 3 9
1 + 2 shouldBe res0 "Hello, " ++ "Scala!" shouldBe res1
Another way to make complex expressions out of simpler expressions is to call methods on expressions:
Methods are applied on expressions using the dot notation.
The object on which the method is applied is named the target object.
Methods can have parameters. They are supplied between parentheses.
In the below examples, the
abs method returns the absolute value of a
number, and the
toUpperCase method returns the target
"Hello, Scala!".toUpperCase shouldBe res0 -42.abs shouldBe res1
Actually, operators are just methods with symbolic names:
3 + 2 == 3.+(2)
The infix syntax allows you to omit the dot and the parentheses.
The infix syntax can also be used with regular methods:
1.to(10) == 1 to 10
Any method with a parameter can be used like an infix operator.
Expressions have a value and a type. The evaluation model defines how to get a value out of an expression. Types classify values.
1 are numbers, their type is
"bar" are text, their type is
The Scala compiler statically checks that you don’t combine incompatible expressions.
Fill the following blank with values whose type is
Int and see the result:
1 to res0
Int: 32-bit integers (e.g.
Double: 64-bit floating point numbers (e.g.
Boolean: boolean values (
String: text (e.g.
Note that type names always begin with an upper case letter.
Here are some more methods of standard types. Can you guess what they do? If you get stuck, try evaluating each statement in turn in a scala REPL to see what the result is.
16.toHexString shouldBe res0 (0 to 10).contains(10) shouldBe true (0 until 10).contains(10) shouldBe res1 "foo".drop(1) shouldBe "oo" "bar".take(2) shouldBe res2