Scala Block Syntax
Scala provides several ways of defining code blocks.
Java-like Curly Braces
def plus1(x:Int, y:Int) : Int = { return x+y; }Short inline
def plus2(x:Int, y:Int) = x+yShort inline compound expression
def plus3(x:Int, y:Int) = { val result = x+y ; result }Block
endidentiferdef plus4(x:Int, y:Int) = x+y end plus4
Factorial with Java-like Curly-brace Conditional Block
The return keyword is optional and typically omitted in Scala code; below is an implementation of fact from Scala Introduction - Slide 10 with explicit block curly braces and return.
def fact(n:Int) : Int = {
println("called with n=%d".format(n))
if n <= 1 then {
println("no recursive call")
return 1
} else {
println("making recursive call")
return n * fact(n - 1)
}
}Class Parameters, Fields, Constructor Code, and toString
Extends the class C from Scala Classes - Slide 8 with a toString method.
class C (f1:Int, val f2:Int, var f3:Int):
val f4 = f1 * f2
var f5 = f2 * f3
println ("Constructing instance of C")
def m (x:Int) : Int =
// cannot reassign to f1, f2, f4
f3 = f3 + 1
f5 = f5 + 1
f1 * f3 * x
end m
override def toString() = "I am a C"
end CCompanion Objects
Companion object has access to the private fields of other instances of the class Scala Classes - Slide 14
class D:
var f1:Int = 0
private val f2:Int = 1
end D
// Companion object to class D (by name convention)
object D:
var f2:Int = 0
def getF2() =
val d = new D()
d.f2 // companion object can access private field
end getF2
end DUsing the class and the companion object reveals the difference in access to the private field f2.
val d = new D()
d.f2 // fails, f2 is private
D.getF2() // succeeds, companion object is allowed to access private field f2