Scala is introduced through small programs that combine pure functions. Its language basics include objects, namespaces, methods, expressions, types, and indentation-based definitions. section 2.0 section 2.1
A small Scala program illustrates several core language features:
- object creates a singleton type that provides a place for related definitions. section 2.1
- def declares methods whose results come from evaluating their right-hand-side expressions. section 2.1
- Type annotations describe parameters and results, while if expressions also produce values. section 2.1
- Pure functions, tail-recursive loops, higher-order functions, and polymorphic functions provide the functional core. section 2.0
Absolute value and formatted output
object MyProgram: def abs(n: Int): Int = if n < 0 then -n else n private def formatAbs(x: Int) = val msg = "The absolute value of %d is %d" msg.format(x, abs(x)) @main def printAbs: Unit = println(formatAbs(-42)) section 2.1
Listing 2.1 A simple Scala program
// A comment!
/* Another comment */
/** A documentation comment */
object MyProgram: #1
def abs(n: Int): Int = #2
if n < 0 then -n #3
else n
private def formatAbs(x: Int) = #4
val msg = "The absolute value of %d is %d" #5
msg.format(x, abs(x)) #6
@main def printAbs: Unit = #7
println(formatAbs(-42))
Browse the complete listing to inspect the program's object, pure function, local value, formatting method, and main definition. section 2.1
