Scala Basics
Running Scala
- Compiled to Java bytecode
- experimental JavaScript backend: Scala.js
- Read-Eval-Print-Loop (REPL)
- fast turnaround
- easy experimentation/testing
- available within many tools: Eclipse IDE, sbt, Scala.jsFiddle, ...
Essentials
- Every value is an object
- Everything is an expression (evaluates to a value)
- Every operation is a method call
Everything is an expression
- No statements
- Reduces the need for return and side-effects
Scala's REPL
- Compiles and executes Scala code immediately
- Start from sbt prompt using 'console'
Command-Line Tools
- For now, we stick to the most simple use case
- Compiling Scala source files:
scalac -d [outdir] [files]
- Running compiled class files:
scala -cp [outdir] [application-object]
- What's
[application-object]?
Scala Applications
object defines a singleton object
- Among others, singleton objects may extend classes and Java interfaces
- Singleton objects may define methods and fields
- Everything within their body is run when the object is used for the first time
- Extending
App turns the object into a Scala application
The main Method
- Applications don't have to extend the
App trait
- Instead, a
main method can be defined explicitly
- The following object can be run on the command-line as follows:
scala -cp [outdir] recfun.Main
Recursive Functions
Example: computing the Fibonacci series
- A series of integer numbers in which each number (Fibonacci number) is the sum
of the two preceding numbers.
- The Fibonacci series starts as follows: 1, 1, 2, 3, 5, 8, ...
Task: write a recursive function that computes the n-th Fibonacci number:
Lists
- Scala has a comprehensive collections library
- In particular, its standard library provides a number of powerful immutable collection types
- Immutable collections have several advantages over mutable collections, e.g., they enable equational
reasoning, and they can safely be accessed concurrently.
- Note: the type
List[T] does not have to be imported; it is an alias of
scala.collection.immutable.List[T].
Classes
- Classes introduce (class) types
- Have members: fields, methods, classes, traits, ...
- Abstract classes may leave members abstract (i.e., without an implementation)
- Instantiation of concrete classes through constructor invocation
- Inheritance:
- Single class inheritance, a class may extend exactly one superclass
- A class may mix in multiple traits
- Members may be overridden (explicitly)
- Subtyping polymorphism
Classes
When compiled, this class will look and behave exactly like the
obvious translation to a Java class. No glue code necessary.
Primary Constructor
- Defined implicitly
- Class parameters are parameters of the primary constructor
- Class body is the body of the primary constructor
- If the superclass constructors take parameters, they have to be passed in the
extends clause
Example
- Write a simple class for modeling cars
- The
Car class should have fields for its make, model, and year
- The fields should be set by the primary constructor
- It should provide a
toString method showing the values of these fields
- Create a stand-alone Scala application that creates a
Car instance and prints it as a string
Constructor parameters and fields
- Assigning constructor parameters to fields becomes verbose quickly
- A
val or var modifier makes a constructor parameter available as a field
Auxiliary Constructors
- The primary constructor is implicit
- Auxiliary constructors are introduced using
def members with name this
- Auxiliary constructors must invoke an earlier-defined constructor
- The primary constructor is always eventually invoked
Traits
- Like Java interfaces, but in addition
- allow concrete methods, fields, types
- Like Scala classes, but without constructor parameters
- Allow (a form of) multiple inheritance
Example
- Define a trait
Convertable with a method openRooftop
- The
openRooftop method should print a simple message
- Create a few cars, some of which mix in the
Convertable trait
What is FP?
- Use of functions (in the mathematical sense)
- referential transparency (no side-effects)
- Immutable objects
- Functions are values
Scala as a Functional Programming Language
- Use val instead of var
- Immutable collections in the standard library
- Leverage function literals and closures
Higher-Order Functions
- Functions that take or return functions
- Almost eliminate the need for loops over collections
Higher-Order Functions: Examples
Collections
- Generic (
List[T], Map[K, V])
- Mutable and immutable implementations (default is immutable)
- Uniform return type principle
- No compiler magic!
Tuples
- Fixed-size, heterogenous
- Example:
val tup: (String, Int) = ("A", 0)
- Alternative syntax:
val tup: (String, Int) = "A" -> 0
- No magic: just the
-> extension method
- Pattern matching enabled
- Emulate multiple results and/or multiple variable definitions
Example
- Given a collection of cars (an immutable
Seq)
- Compute a collection of the brands that are represented
Example: Solution
- Given a collection of cars (an immutable
Seq)
- Compute a collection of the brands that are represented
Everything is an object
- Closures are objects, too
- Instances of trait
Function1[A, B] (compiler generated)
Syntactic Sugar
- Why can I call
succ(10)?
f(args) is desugared to f.apply(args)
- You can define your own
apply methods
- ...can I subclass
FunctionN?
Function Subtypes
- Yes! Many collections are functions.
- Sequences are
Int => T
- Sets are
T => Boolean
- Maps are
K => V
For-comprehensions
- More general than for-loops
- Used to iterate, filter and generate new collections
For-comprehensions
- Translated to calls to
filter, map, flatMap
- Readily available to any class implementing those methods
- Can be used to query a database
- Implement
filter, map, flatmap to generate and forward SQL
- SLICK, Squeryl
Building and Testing
- Testing
- ScalaTest
- specs2
- ScalaCheck: generate random test inputs
- any Java testing framework
- Building
- Build tools: sbt, Maven, Gradle, ant, ...
- IntelliJ Survey at Scala Days 2013 (blog):
ScalaCheck: Property-based testing
Pattern matching
- A way to match and deconstruct structured data
- A powerful
switch statement (expression, really)
Scala Open Source Project
- Scala compiler, standard library, and modules open-source (BSD license)
- Contributions
Scala modules
- scala-swing
- scala-async
- scala-pickling
- scala-parser-combinators
←
→
#
/