Basics lesson of the workshop.
println("Hello world")
Number literals
true ⇒ Boolean
1 ⇒ Int
1L ⇒ Long
1.0 ⇒ Double
1.0f ⇒ Float
'1' ⇒ Char
"1" ⇒ String
Numbers are objects. All objects inherit from AnyRef
.
Operators are functions and functions are operators
1 + 1 ⇔ 1.+(1)
"Hello world".indexOf("w") ⇔ "Hello world" indexOf "w"
Equality ==
is equals
reference equality by eq
.
There are more operators (logical, bitwise, …).
Variables can be change
var i = 1
i = i + 1
i
Values can not be changed
val i = 1
i = i + 1 ⇒ compile error
i
def
and val
are executed differently
var i = 1
val j = i + 1
def k = i + 1
j
k
i = i + 1
j
k
lazy
can defer val
(Scala console)
The type can be declared explicitly or be calculated by the compiler.
val i = 1
val j: Int = 1
val k: Double = 1
Types are also working for def
def i: Int = 1 + 1
val j: Int = i
Define a simple function.
1 ⇒ Int
(x: Int) => x + 1 ⇒ (Int) => Int
Name a function with val
or def
val i = (x: Int) => x + 1
i ⇒ returns function object
i.apply(1) ⇒ executes function
i(1) ⇒ short cut
i eq i ⇒ true
def j = (x: Int) => x + 1 ⇔ def j: (Int) => Int = (x) => x + 1 ⇔ def j: (Int) => Int = _ + 1
j
j(1)
j eq j ⇒ false
def
creates a function, that can have parameters
def k(x: Int): Int = x + 1
k ⇒ compile error
k(1)
Call by value is default behavior. Call by name has a short cut.
def i(x: Int): Int = x + 1
def j(x: () => Int): Int = x() + 1
j(() => 1)
def k(x: => Int): Int = x + 1
k(1)
def i(x: Int)(y: Int) = x + y
i(1)(1)
def j = i(1) _
j(1)