If you know both, Java and Python you will grasp Scala efortless. However if this is your first programming language, don't warry. We will explain the syntax as if Scala would be the only language in the world. It is not required to know either Java nor Python before learning Scala.
Let's get started with an example:
//simple Scala program
object Hello {
def main(args: Array[String]) = {
println("Hello, world")
}
}
Notes:
First run:
We use "repl.io" website to host free examples that will be available as "homeworks" in this tutorial. You can log-in using your GitHub account and you can create your own code or you can open and run our example on-line using this link: scala-hello.Next we will introduce basic elements of Scala syntax as if you have never learned a programming language before. Sorry if this is borring for an experienced developer. You must understand the fundamentals before learning the cool stuff.
Scala code must be written in text files having extension *.scala. One scala project can have several files. One of the file contains the program entry point. It is called: "main method" very similar to Java.
The "main method" is the entry point of a Scala program. The Java Virtual Machine requires a main method, named main, that takes one argument: an array of strings. You can define the Main method as part of an object:
//the main method
object Main {
def main(args: Array[String]): Unit =
println("Hello, Scala developer!")
}
A variable is an identifier that we assign to a location in memory that holds a value for a while. This value can or can't be changed depending on the way it was defined. This is Scala has two kind of variables:
//define tree identifiers: x,y,z
val x = 1 //value (constant)
var y = 2 //variable (mutable)
var z: int = 0 //define integer z
Scala is an "expression oriented" language, unlike Java that is "statement oriented". That means you can create free expressions. Scala free expressions are evaluated by the compiler and used to return a value.
//numeric expressions
1
2 + 2
(a + b)/(c+d)
//string expression
"hello" + "world"
//boolean expressions
!true
(a || b) && c
You can define a code block that is a group of statements enclosed in squigly brackets. A block can have a result, that is the value of last expression from the block. Check-out this example:
//using a block
val x: int = {
val x = 1 + 1
x + 1
}
println(x)// expected output: 3
You do not have to learn all keywords right now. Just for your information, Scala has about 40 keywords. These are reserved, you should never use them to create your own identifiers.
abstract | extends | implicit | super | val |
case | false | override | this | var |
catch | final | package | throw | while |
class | finally | private | trait | with |
def | for | protected | true | yield |
do | forSome | return | try | new |
else | if | sealed | type | object |
null | match | lazy | import |
Next are Scala "rezerved symbols", though: "<: and "=>" are technically keywords, the rest of these symbols would be "punctuation symbols". However we call them, they must be learned so here is the list of symbols we have found in documentation.
symbol | Description |
---|---|
<- | Used on for-comprehensions, to separate pattern from generat |
=> | Used for function types, function literals and import renaming |
( ) | Delimit expressions and parameters |
[ ] | Delimit type parameters |
{ } | Delimit blocks |
. | Method call and path separator |
// | Line comments |
/* */ | Block comments |
# | Used in type notations |
: | Type declaration or context bounds |
<: >: | Upper and lower bounds |
<% | View bounds (deprecated) |
" """ | Strings |
' | Indicate symbols and characters |
@ | Annotations and variable binding on pattern matching |
` | Denote constant or enable arbitrary identifiers |
, | Separator for a list ofthings |
; | Statement separator |
_* | vararg expansion |
_ | Many different meanings |
We have learned so far that Scala is an expression based language remember? Expressions are created with identifiers, constants, symbols and operators. The operators are: one, two or tree special characters groupped together, and spearated by a space before and after the group. Depending on the result, we clasify the operators as:
Operator type | Description |
---|---|
Bitwise Operators | Can operate on integer numbers, return integer. |
Logical Operators | Can operate on Booleans, return Boolean |
Comparison Operators | Can operate on numbers, return Boolean |
Assignment Operators | Can operate on a variable and expression of same type |
Arithmetic Operators | Can operate on numbers, return numbers |
Given two binary numbers A = 0011 and B=1010 here are the operators and results:
Operator | Meaning | Example | Result | |
---|---|---|---|---|
& | bit and | A & B | 0010 | |
| | bit or | A | B | 1011 | |
^ | bit xor | A ^ B | 1001 | |
~ | bit not | ~A | 1100 | |
<< | shift left | 2 << A | 1100 | |
>> | shift right | B >> 2 | 0010 |
These operators are also known as Boolean operators. They accept arguments of type Boolean and return Boolean results: true or false. Notice in Scala true is greater then false.
Operator | Name | Description | Expression | Result |
---|---|---|---|---|
&& | and | Returns true if both statements are true | a && b | true |
|| | or | Returns true if one of the statements is true | a || b | true |
! | not | Reverse the result, returns false if the result is true | !a | false |
These operators are used to in logical expressions but they compare any kind of things. In fact they are polimorphic operators. Can compare number primarly but also boolean or string operands. Important fact to know is that alwais return true/false Boolean values.
Operator | Name | Example |
---|---|---|
== | Equal to | x == y |
!= | Not equal | x != y |
> | Greater than | x > y |
< | Less than | x < y |
>= | Greater than or equal to | x >= y |
<= | Less than or equal to | x <= y |
These operators are also called "in-place" operators or "variable modifiers". Have double role: make an arithmetic operation and assign the result to left operand. The right operand can be a constant, variable or expression that return same tipe as the left operand.
Operator | Name | Expression | Equivalent |
---|---|---|---|
= | Assignment | x = 1 | x = 1 |
+= | Addition | x += 1 | x = x + 1 |
-= | Subtraction | x -= 1 | x = x - 1 |
*= | Multiplication | x *= 1 | x = x * 1 |
/= | Division | x /= 1 | x = x / 1 |
%= | Modulo | x %= 1 | x = x % 1 |
&= | Bitweese and | x &= 1 | x = x & 1 |
|= | Bitweese or | x |= 1 | x = x | 1 |
^= | Bitweese not | x ^= 1 | x = x ^ 1 |
>>= | left shift | x >>= 1 | x = x >> 1 |
<<= | right shift | x <<= 1 | x = x << 1 |
These operators are used to create numeric expressions.
Operator | Name | Description | Example |
---|---|---|---|
+ | Addition | Adds together two values | x + y |
- | Subtraction | Subtracts one value from another | x - y |
* | Multiplication | Multiplies two values | x * y |
/ | Division | Divides one value by another | x / y |
% | Modulus | Returns the division remainder | x % y |
Read next: Data Types