liveBook · Manning

Scala

As explained in Functional Programming in Scala, Second Edition

Scala is a statically typed programming language that combines object-oriented and functional programming features and runs on the Java Virtual Machine.

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

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Introduces a complete program, syntax, objects, methods, types, recursion, and higher-order functions without pursuing advanced implementation internals.
Examples
Demonstrates an absolute-value function, formatted strings, local values, an object, and a main entry point.
What it assumes
Assumes no Scala or functional-programming background and teaches syntax by examining complete code piece by piece.
What you can do after
Build a small Scala program with objects, typed methods, conditionals, formatting, and a main entry point.
How it connects
Connects objects, namespaces, pure functions, tail recursion, higher-order functions, and polymorphic functions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in Scala, Second Edition. The section links point to the parts of the book it draws on.