\PassOptionsToPackage{unicode=true}{hyperref} % options for packages loaded elsewhere
\PassOptionsToPackage{hyphens}{url}
%
\documentclass[]{article}
\usepackage{lmodern}
\usepackage{amssymb,amsmath}
\usepackage{ifxetex,ifluatex}
\usepackage{fixltx2e} % provides \textsubscript
\ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex
  \usepackage[T1]{fontenc}
  \usepackage[utf8]{inputenc}
  \usepackage{textcomp} % provides euro and other symbols
\else % if luatex or xelatex
  \usepackage{unicode-math}
  \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase}
\fi
% use upquote if available, for straight quotes in verbatim environments
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
% use microtype if available
\IfFileExists{microtype.sty}{%
\usepackage[]{microtype}
\UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
}{}
\IfFileExists{parskip.sty}{%
\usepackage{parskip}
}{% else
\setlength{\parindent}{0pt}
\setlength{\parskip}{6pt plus 2pt minus 1pt}
}
\usepackage{hyperref}
\hypersetup{
            pdftitle={CSci 658: Software Language Engineering Notes on Scala for Java Programmers},
            pdfauthor={H. Conrad Cunningham},
            pdfborder={0 0 0},
            breaklinks=true}
\urlstyle{same}  % don't use monospace font for urls
\usepackage{color}
\usepackage{fancyvrb}
\newcommand{\VerbBar}{|}
\newcommand{\VERB}{\Verb[commandchars=\\\{\}]}
\DefineVerbatimEnvironment{Highlighting}{Verbatim}{commandchars=\\\{\}}
% Add ',fontsize=\small' for more characters per line
\newenvironment{Shaded}{}{}
\newcommand{\AlertTok}[1]{\textcolor[rgb]{1.00,0.00,0.00}{\textbf{#1}}}
\newcommand{\AnnotationTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textbf{\textit{#1}}}}
\newcommand{\AttributeTok}[1]{\textcolor[rgb]{0.49,0.56,0.16}{#1}}
\newcommand{\BaseNTok}[1]{\textcolor[rgb]{0.25,0.63,0.44}{#1}}
\newcommand{\BuiltInTok}[1]{#1}
\newcommand{\CharTok}[1]{\textcolor[rgb]{0.25,0.44,0.63}{#1}}
\newcommand{\CommentTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textit{#1}}}
\newcommand{\CommentVarTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textbf{\textit{#1}}}}
\newcommand{\ConstantTok}[1]{\textcolor[rgb]{0.53,0.00,0.00}{#1}}
\newcommand{\ControlFlowTok}[1]{\textcolor[rgb]{0.00,0.44,0.13}{\textbf{#1}}}
\newcommand{\DataTypeTok}[1]{\textcolor[rgb]{0.56,0.13,0.00}{#1}}
\newcommand{\DecValTok}[1]{\textcolor[rgb]{0.25,0.63,0.44}{#1}}
\newcommand{\DocumentationTok}[1]{\textcolor[rgb]{0.73,0.13,0.13}{\textit{#1}}}
\newcommand{\ErrorTok}[1]{\textcolor[rgb]{1.00,0.00,0.00}{\textbf{#1}}}
\newcommand{\ExtensionTok}[1]{#1}
\newcommand{\FloatTok}[1]{\textcolor[rgb]{0.25,0.63,0.44}{#1}}
\newcommand{\FunctionTok}[1]{\textcolor[rgb]{0.02,0.16,0.49}{#1}}
\newcommand{\ImportTok}[1]{#1}
\newcommand{\InformationTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textbf{\textit{#1}}}}
\newcommand{\KeywordTok}[1]{\textcolor[rgb]{0.00,0.44,0.13}{\textbf{#1}}}
\newcommand{\NormalTok}[1]{#1}
\newcommand{\OperatorTok}[1]{\textcolor[rgb]{0.40,0.40,0.40}{#1}}
\newcommand{\OtherTok}[1]{\textcolor[rgb]{0.00,0.44,0.13}{#1}}
\newcommand{\PreprocessorTok}[1]{\textcolor[rgb]{0.74,0.48,0.00}{#1}}
\newcommand{\RegionMarkerTok}[1]{#1}
\newcommand{\SpecialCharTok}[1]{\textcolor[rgb]{0.25,0.44,0.63}{#1}}
\newcommand{\SpecialStringTok}[1]{\textcolor[rgb]{0.73,0.40,0.53}{#1}}
\newcommand{\StringTok}[1]{\textcolor[rgb]{0.25,0.44,0.63}{#1}}
\newcommand{\VariableTok}[1]{\textcolor[rgb]{0.10,0.09,0.49}{#1}}
\newcommand{\VerbatimStringTok}[1]{\textcolor[rgb]{0.25,0.44,0.63}{#1}}
\newcommand{\WarningTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textbf{\textit{#1}}}}
\setlength{\emergencystretch}{3em}  % prevent overfull lines
\providecommand{\tightlist}{%
  \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
\setcounter{secnumdepth}{0}
% Redefines (sub)paragraphs to behave more like sections
\ifx\paragraph\undefined\else
\let\oldparagraph\paragraph
\renewcommand{\paragraph}[1]{\oldparagraph{#1}\mbox{}}
\fi
\ifx\subparagraph\undefined\else
\let\oldsubparagraph\subparagraph
\renewcommand{\subparagraph}[1]{\oldsubparagraph{#1}\mbox{}}
\fi

% set default figure placement to htbp
\makeatletter
\def\fps@figure{htbp}
\makeatother

\usepackage{caption}
\DeclareCaptionLabelFormat{nolabel}{}
\captionsetup{labelformat=nolabel}

\title{CSci 658: Software Language Engineering\\
Notes on Scala for Java Programmers}
\author{\textbf{H. Conrad Cunningham}}
\date{\textbf{17 February 2018}}

\begin{document}
\maketitle

{
\setcounter{tocdepth}{4}
\tableofcontents
}
\href{http://www.cs.olemiss.edu/~hcc}{H. Conrad Cunningham}\\
Professor of \href{https://www.cs.olemiss.edu}{Computer and Information
Science}\\
\href{http://www.olemiss.edu}{University of Mississippi}\\
211 Weir Hall\\
P.O. Box 1848\\
University, MS 38677\\
(662) 915-5358

\textbf{Advisory}: The HTML version of this document may require use of
a browser that supports the display of MathML. A good choice as of
Februlary 2018 is a recent version of Firefox from Mozilla.

\hypertarget{notes-on-scala-for-java-programmers}{%
\section{Notes on Scala for Java
Programmers}\label{notes-on-scala-for-java-programmers}}

\hypertarget{introduction}{%
\subsection{Introduction}\label{introduction}}

This is an introduction to Scala for programmers who have completed the
equivalent of the Java-based Computer Science I-II-III (CSci
111-112-211) sequence at the University of Mississippi.

I adapt and expand the document
\href{http://docs.scala-lang.org/tutorials/scala-for-java-programmers.html}{``A
Scala Tutorial for Java Programmers''} by Michel Schinz and Phillipp
Haller to better meet the needs of my Scala-based courses (to explain
some items more thoroughly, improve the narrative, and make the document
accessible).

\hypertarget{a-first-example-hello-world}{%
\subsection{A First Example: Hello
World}\label{a-first-example-hello-world}}

A ``Hello, world!'' program is the obligatory first example to give when
introducing a new language. We can write a program \texttt{HelloWorld}
as follows in Scala:

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{object}\NormalTok{ HelloWorld \{}
        \KeywordTok{def} \FunctionTok{main}\NormalTok{(args: Array[String]) \{}
            \FunctionTok{println}\NormalTok{(}\StringTok{"Hello, world!"}\NormalTok{)}
\NormalTok{        \}}
\NormalTok{    \}}
\end{Highlighting}
\end{Shaded}

What Scala features do we use here in relation to Java?

\begin{itemize}
\item
  Keyword \texttt{object} declares a \emph{singleton object} named
  \texttt{HelloWorld}. An object is essentially a class with a single
  instance. The body of the object is enclosed in braces following the
  name.
\item
  The keyword \texttt{def} introduces a method definition.
\item
  In a declaration, a colon (\texttt{:}) separates the name from its
  type.
\item
  Method \texttt{main} takes the command line arguments as its
  parameter, which is an array of strings.
\item
  The \texttt{main} method is a procedure and, hence, has no return type
  declared. The body of the method is enclosed in braces following the
  method header.
\item
  The \texttt{main} method is not declared as \texttt{static} as in
  Java. Static members do not exist in Scala. We can use singleton
  objects instead.
\item
  The body of \texttt{main} has a single call to predefined method
  \texttt{println}.
\end{itemize}

\hypertarget{compiling-the-example}{%
\subsubsection{Compiling the example}\label{compiling-the-example}}

We can use the \texttt{scalac} command (similar to the \texttt{javac}
command) to invoke the Scala compiler. If the above Scala program is
stored in file \texttt{HelloWorld.scala}, we can compile it from the
command line as follows:

\begin{Shaded}
\begin{Highlighting}[]
    \ExtensionTok{scalac}\NormalTok{ HelloWorld.scala}
\end{Highlighting}
\end{Shaded}

The above compiles the Scala source file and generates a few class files
in the current directory.

File \texttt{HelloWorld.class} contains a class that can be executed.

\hypertarget{running-the-example}{%
\subsubsection{Running the example}\label{running-the-example}}

We can use the \texttt{scala} command (similar to the \texttt{java}
command) to execute the \texttt{main} method. Execution of the program
prints the ``Hello, World'' string to the console.

\begin{Shaded}
\begin{Highlighting}[]
    \OperatorTok{>} \ExtensionTok{scala}\NormalTok{ -classpath . HelloWorld}

    \ExtensionTok{Hello}\NormalTok{, world!}
\end{Highlighting}
\end{Shaded}

\hypertarget{interaction-with-java}{%
\subsection{Interaction with Java}\label{interaction-with-java}}

Scala code can interact with Java code. Package \texttt{java.lang} is
imported by default and other packages can be imported explicitly.

Consider a program to obtain and format the current date according to
the conventions used in a specific country, say France.

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{import}\NormalTok{ java.}\FunctionTok{util}\NormalTok{.\{Date, Locale\}}
    \KeywordTok{import}\NormalTok{ java.}\FunctionTok{text}\NormalTok{.}\FunctionTok{DateFormat}
    \KeywordTok{import}\NormalTok{ java.}\FunctionTok{text}\NormalTok{.}\FunctionTok{DateFormat}\NormalTok{._}

    \KeywordTok{object}\NormalTok{ FrenchDate \{}
        \KeywordTok{def} \FunctionTok{main}\NormalTok{(args: Array[String]) \{}
            \KeywordTok{val}\NormalTok{ now = }\KeywordTok{new}\NormalTok{ Date}
            \KeywordTok{val}\NormalTok{ df = }\FunctionTok{getDateInstance}\NormalTok{(LONG, Locale.}\FunctionTok{FRANCE}\NormalTok{)}
            \FunctionTok{println}\NormalTok{(df format now)}
\NormalTok{        \}}
\NormalTok{    \}}
\end{Highlighting}
\end{Shaded}

Java's class libraries such as \texttt{Date} and \texttt{DateFormat} can
be called directly from Scala code.

The Scala \texttt{import} statement is more powerful than Java's. It
can:

\begin{itemize}
\item
  Import multiple classes by enclosing names in braces.

  The first line above imports the \texttt{Data} and \texttt{Locale}
  classes from Java package \texttt{java.util}.
\item
  Import everything in a package or class by using an underscore
  character (\texttt{\_}) instead of a Java's asterisk (\texttt{*}).

  The third line imports all members of the \texttt{DateFormat} class,
  making static method \texttt{getDateInstance} and static field
  \texttt{LONG} visible.
\end{itemize}

The \texttt{main} method in the \texttt{FrenchDate} object:

\begin{itemize}
\item
  Creates an instance of Java's \texttt{Date} class, thus getting the
  current date
\item
  Uses the imported static method \texttt{getDateInstance} to format the
  date appropriately for France using \texttt{Locale.France}
\item
  Prints the current date formatted according to the localized
  \texttt{DateFormat} instance
\end{itemize}

The \texttt{main} method declares two local ``variables'' in its body:
\texttt{now} and \texttt{df}. Note that:

\begin{itemize}
\item
  Both are declared with \texttt{val}. After initialization, Scala does
  not allow further assignments to a \texttt{val}.

  The alternative is \texttt{var}. Scala does allow assignments to a
  \texttt{var}; it is like an ordinary variable in Java.

  Although we cannot change the binding of a \texttt{val} to an object,
  Scala does allow the internal state of the object to be changed.
\item
  Although Scala is statically typed like Java, neither of these
  variables are given explicit types. The types of the variables are
  {[}\emph{inferred}
  {]}\url{https://en.wikipedia.org/wiki/Type_inference}) by the compiler
  from the type of the initializing expression.
\end{itemize}

Scala methods taking one explicit argument can be written in infix
syntax such as

\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{    df format now}
\end{Highlighting}
\end{Shaded}

which is the same as the method call

\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{    df}\FunctionTok{.format}\NormalTok{(now)}
\end{Highlighting}
\end{Shaded}

This feature has important consequences, as we discuss below.

It is also possible to inherit from Java classes and implement Java
interfaces directly in Scala.

\hypertarget{everything-is-an-object}{%
\subsection{Everything is an Object}\label{everything-is-an-object}}

Scala is a pure object-oriented language. \emph{Everything} is an
object, including numbers and functions.

Scala does not distinguish primitive types (e.g., \texttt{boolean} and
\texttt{int}) from reference types (e.g., objects). It enables us to
manipulate functions as first-class values.

\hypertarget{numbers-are-objects}{%
\subsubsection{Numbers are objects}\label{numbers-are-objects}}

Since numbers are objects, they also have methods. For example, the
expression

\begin{Shaded}
\begin{Highlighting}[]
    \DecValTok{1}\NormalTok{ + }\DecValTok{2}\NormalTok{ * }\DecValTok{3}\NormalTok{ / x}
\end{Highlighting}
\end{Shaded}

is equivalent to the expression

\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{    (}\DecValTok{1}\NormalTok{).+(((}\DecValTok{2}\NormalTok{).*(}\DecValTok{3}\NormalTok{))./(x))}
\end{Highlighting}
\end{Shaded}

which shows the method calls explicitly.

In Scala, the ``operator'' symbols (e.g., \texttt{+}, \texttt{*},
\texttt{/}) are valid identifiers. The parentheses around numbers are
necessary because Scala's lexical analyzer uses a longest-match rule for
tokens, breaking expression

\begin{Shaded}
\begin{Highlighting}[]
    \FloatTok{1.}\NormalTok{+(}\DecValTok{2}\NormalTok{)}
\end{Highlighting}
\end{Shaded}

into the tokens \texttt{1.}, \texttt{+}, and \texttt{2}. This results in
\texttt{1.} being interpreted as a \texttt{Double}.

\hypertarget{functions-are-objects}{%
\subsubsection{Functions are objects}\label{functions-are-objects}}

Because Scala functions are objects, we can:

\begin{itemize}
\item
  pass a function as an argument to or return a function as a result
  from another function.

  That is, Scala has
  \href{https://en.wikipedia.org/wiki/Higher-order_function}{\emph{higher-order}}
  functions.
\item
  store a function in a variable or data structure.

  That is, Scala's functions are
  \href{https://en.wikipedia.org/wiki/First-class_function}{\emph{first-class}}
  values.
\end{itemize}

These are key features of
\href{https://en.wikipedia.org/wiki/Functional_programming}{\emph{functional
programming}}.

Consider the \texttt{Timer} program below. It includes a timer function
named \texttt{oncePerSecond} that performs some action every second. The
specific action performed is encoded as a \emph{call-back} function
passed into \texttt{oncePerSecond} as an argument.

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{object}\NormalTok{ Timer \{}
        \KeywordTok{def} \FunctionTok{oncePerSecond}\NormalTok{(callback: () => Unit) \{}
            \KeywordTok{while}\NormalTok{ (}\KeywordTok{true}\NormalTok{) \{ }\FunctionTok{callback}\NormalTok{(); Thread sleep }\DecValTok{1000}\NormalTok{ \}}
\NormalTok{        \}}
        \KeywordTok{def} \FunctionTok{timeFlies}\NormalTok{() \{}
            \FunctionTok{println}\NormalTok{(}\StringTok{"time flies like an arrow..."}\NormalTok{)}
\NormalTok{        \}}
        \KeywordTok{def} \FunctionTok{main}\NormalTok{(args: Array[String]) \{}
            \FunctionTok{oncePerSecond}\NormalTok{(timeFlies)}
\NormalTok{        \}}
\NormalTok{    \}}
\end{Highlighting}
\end{Shaded}

The type of the call-back function is
\texttt{()\ =\textgreater{}\ Unit}. This means it is a function that
takes no arguments and returns nothing. The type \texttt{Unit} is
similar to \texttt{void} in C/C++.

Function \texttt{oncePerSecond} calls the \texttt{Thread.sleep} method
(from \texttt{java.lang}) and uses an infinite \texttt{while} loop to
repeat the call-back action every second.

The \texttt{main} function calls this timer function, passing a
call-back function that prints the string ``time flies like an
arrow\ldots{}'' on the console. The program endlessly prints this string
every second.

The program uses the predefined Scala method \texttt{println} instead
the like-named Java method from \texttt{System.out}.

\hypertarget{anonymous-functions}{%
\subsubsection{Anonymous functions}\label{anonymous-functions}}

The \texttt{Timer} program in the subsection above can be refined by
replacing the function \texttt{timeFlies} by an
\href{https://en.wikipedia.org/wiki/Anonymous_function}{\emph{anonymous
function}} as shown below:

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{object}\NormalTok{ TimerAnonymous \{}
        \KeywordTok{def} \FunctionTok{oncePerSecond}\NormalTok{(callback: () => Unit) \{}
            \KeywordTok{while}\NormalTok{ (}\KeywordTok{true}\NormalTok{) \{ }\FunctionTok{callback}\NormalTok{(); Thread sleep }\DecValTok{1000}\NormalTok{ \}}
\NormalTok{        \}}
        \KeywordTok{def} \FunctionTok{main}\NormalTok{(args: Array[String]) \{}
            \FunctionTok{oncePerSecond}\NormalTok{(() =>}
                \FunctionTok{println}\NormalTok{(}\StringTok{"time flies like an arrow..."}\NormalTok{))}
\NormalTok{        \}}
\NormalTok{    \}}
\end{Highlighting}
\end{Shaded}

In the anonymous function, a right arrow \texttt{=\textgreater{}}
separates the function's argument list from its body expression.

In this example, the argument list is empty, shown by the empty pair of
parentheses on the left.

\hypertarget{classes}{%
\subsection{Classes}\label{classes}}

Like Java, Scala is a class-based language. However, Scala classes can
have parameters. Consider the following class \texttt{Complex} for
representing complex numbers:

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{class} \FunctionTok{Complex}\NormalTok{(real: Double, imaginary: Double) \{}
        \KeywordTok{def} \FunctionTok{re}\NormalTok{() = real}
        \KeywordTok{def} \FunctionTok{im}\NormalTok{() = imaginary}
\NormalTok{    \}}
\end{Highlighting}
\end{Shaded}

The \texttt{Complex} class takes two arguments, the real and imaginary
parts of the complex number. In the \texttt{Complex} class, these become
\texttt{val} fields of the object (i.e., class instance) that are only
visible and accessible from inside the object. (This visibility is
\texttt{private{[}this{]}}, a type of visibility that does not occur in
Java.)

The default constructor is built into the \texttt{class} syntax. We pass
values for these arguments when we create an instance of class
\texttt{Complex}, as follows:

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{new} \FunctionTok{Complex}\NormalTok{(}\FloatTok{1.5}\NormalTok{, }\FloatTok{2.3}\NormalTok{)}
\end{Highlighting}
\end{Shaded}

This causes all statements in the class definition to be executed.

The \texttt{Complex} class defines function methods \texttt{re} and
\texttt{im}, which provide access to the two parts of the complex
number. That is, these are \emph{accessor}, or \emph{getter}, methods.

We declare a function with an \texttt{=} between the function's header
(i.e., name and parameter list) and its body. The body is an expression
that is evaluated when the function is called. If the body itself
consists of a sequence of expressions, we enclose it in braces. The
value of last expression executed is the value of the body.

In \texttt{Complex}, the compiler infers the return types for methods
\texttt{re()} and \texttt{im()} by examining the right-hand sides and
deducing that both return a value of type \texttt{Double}. The compiler
gives an error message when it cannot infer the type of a method or
variable.

Some Scala programmers suggest that the types be omitted whenever
possible and only inserted when necessary.

However, your instructor considers it better software engineering
practice to explicitly specify the types of all \emph{public} features
of a class or package such as the \texttt{re()} and \texttt{im()}
methods.

But, for internal features of a class or method, it is convenient and
safe to use type inference. For example, we did not give explicit types
for the \texttt{now} and \texttt{df} values in the \texttt{FrenchDate}
object shown in a previous section.

\hypertarget{methods-without-arguments}{%
\subsubsection{Methods without
arguments}\label{methods-without-arguments}}

To call the methods \texttt{re} and \texttt{im}, we must put an empty
pair of parentheses after their names:

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{object}\NormalTok{ ComplexNumbers \{}
        \KeywordTok{def} \FunctionTok{main}\NormalTok{(args: Array[String]) \{}
            \KeywordTok{val}\NormalTok{ c = }\KeywordTok{new} \FunctionTok{Complex}\NormalTok{(}\FloatTok{1.2}\NormalTok{, }\FloatTok{3.4}\NormalTok{)}
            \FunctionTok{println}\NormalTok{(}\StringTok{"imaginary part: "}\NormalTok{ + c.}\FunctionTok{im}\NormalTok{())}
\NormalTok{        \}}
\NormalTok{    \}}
\end{Highlighting}
\end{Shaded}

We can eliminate the empty parameter list by defining \texttt{re} and
\texttt{im} as methods \emph{without arguments} instead of \emph{with
zero arguments}. We simply omit the parentheses in the method
definition, as shown below:

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{class} \FunctionTok{Complex}\NormalTok{(real: Double, imaginary: Double) \{}
        \KeywordTok{def}\NormalTok{ re = real}
        \KeywordTok{def}\NormalTok{ im = imaginary}
\NormalTok{    \}}
\end{Highlighting}
\end{Shaded}

\hypertarget{inheritance-and-overriding}{%
\subsubsection{Inheritance and
overriding}\label{inheritance-and-overriding}}

All classes in Scala inherit from a superclass. If no super class is
given explicitly, then the superclass is \texttt{scala.AnyRef} by
default.

Like Java, a Scala class inherits all methods from its superclass by
default.

Like Java, a Scala class may override individual methods by giving new
definitions.

Unlike Java, a Scala method that overrides a superclass method must be
explicitly declared with the \texttt{override} modifier. This is to
reduce the possibility of class overriding a superclass method by
accident.

For example, the\texttt{Complex} class can redefine the
\texttt{toString} method inherited from \texttt{AnyRef}.

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{class} \FunctionTok{Complex}\NormalTok{(real: Double, imaginary: Double) \{}
        \KeywordTok{def}\NormalTok{ re = real}
        \KeywordTok{def}\NormalTok{ im = imaginary}
        \KeywordTok{override} \KeywordTok{def} \FunctionTok{toString}\NormalTok{() =}
            \StringTok{""}\NormalTok{ + re + (}\KeywordTok{if}\NormalTok{ (im < }\DecValTok{0}\NormalTok{) }\StringTok{""} \KeywordTok{else} \StringTok{"+"}\NormalTok{) + im + }\StringTok{"i"}
\NormalTok{    \}}
\end{Highlighting}
\end{Shaded}

The new definition of \texttt{toString()} overrides the definition for
\texttt{Complex} objects. However, in doing so, it uses the default
definitions of \texttt{toString()} for \texttt{Double} by its references
to \texttt{re} and \texttt{im} in the string concatenation.

\hypertarget{case-classes-and-pattern-matching}{%
\subsection{Case Classes and Pattern
Matching}\label{case-classes-and-pattern-matching}}

In programming, we often use trees and other hierarchical data
structures.

We can illustrate how to implement a tree in Scala using a small
calculator program for simple arithmetic expressions composed of sums,
integer constants, and variables. Examples of such expressions are
\texttt{1+2} and \texttt{(x+x)+(7+y)}.

We can represent expressions naturally with a tree, where nodes are
operations (e.g., addition) and leaves are values (e.g., constants or
variables).

In Java, we can represent such a tree using an abstract superclass for
the trees and a concrete subclass for each kind of internal and leaf
node. The abstract class defines the common interface to the tree and
the concrete subclasses define the specific features of a node.

In functional programming languages such as Haskell, we can define an
\href{https://en.wikipedia.org/wiki/Algebraic_data_type}{\emph{algebraic
data type}} for the same purpose. These types often enable us to express
programs concisely by using pattern matching constructs.

Scala combines the concepts of classes and algebraic data types into its
\emph{case classes}. Consider the example:

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{abstract} \KeywordTok{class}\NormalTok{ Tree }
    \KeywordTok{case} \KeywordTok{class} \FunctionTok{Sum}\NormalTok{(l: Tree, r: Tree) }\KeywordTok{extends}\NormalTok{ Tree }
    \KeywordTok{case} \KeywordTok{class} \FunctionTok{Var}\NormalTok{(n: String) }\KeywordTok{extends}\NormalTok{ Tree }
    \KeywordTok{case} \KeywordTok{class} \FunctionTok{Const}\NormalTok{(v: Int) }\KeywordTok{extends}\NormalTok{ Tree }
\end{Highlighting}
\end{Shaded}

Here, we define \texttt{Sum}, \texttt{Var} and \texttt{Const} as case
classes. These differ from from standard classes in several ways:

\begin{itemize}
\item
  We can create an instance without using the keyword \texttt{new}
  keyword, for example, we can write \texttt{Const(5)} instead of
  \texttt{new\ Const(5)}.
\item
  The compiler automatically generates getter functions for the
  constructor parameters. That is, it is possible to get the value of
  the \texttt{v} constructor parameter of some instance \texttt{c} of
  class \texttt{Const} just by writing \texttt{c.v}.
\item
  The compiler supplies default definitions for the methods
  \texttt{equals} and \texttt{hashCode}. These work on the
  \emph{structure} of the instances and not on their identities.
\item
  The compiler provides a default definition for method
  \texttt{toString}, which prints the value in a ``source'' form. For
  example, the tree for expression \texttt{x+1} prints as
  \texttt{Sum(Var(x),Const(1))}.
\item
  Instances of these classes can be decomposed through \emph{pattern
  matching} as we see below.
\end{itemize}

These features enable us to use Scala case classes much like we would
use algebraic data types in a functional language.

To explore the use of case classes, consider a function to evaluate an
expression in some \emph{environment}. The purpose of an environment is
to associate values with variables.

For example, the expression \texttt{x+1} evaluated in an environment
that associates the value \texttt{5} with the variable \texttt{x},
written \texttt{\{\ x\ -\textgreater{}\ 5\ \}}, gives \texttt{6} as
result.

An environment is just a function that associates a value with a
(variable) name. The environment \texttt{\{\ x\ -\textgreater{}\ 5\ \}}
given above can be written as a Scala function as follows:

\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{    \{ }\KeywordTok{case} \StringTok{"x"}\NormalTok{ => }\DecValTok{5}\NormalTok{ \}}
\end{Highlighting}
\end{Shaded}

This notation defines a function that, when given the string
\texttt{"x"} as argument, returns the integer \texttt{5}, and,
otherwise, fails and throws an exception.

An environment is a function of type
\texttt{String\ =\textgreater{}\ Int}. To simplify our evaluation
program, we define the name \texttt{Environment} to be an alias for this
type using the following declaration:

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{type}\NormalTok{ Environment = String => Int }
\end{Highlighting}
\end{Shaded}

We can now define the evaluation function in Scala as follows:

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{def} \FunctionTok{eval}\NormalTok{(t: Tree, env: Environment): Int = t }\KeywordTok{match}\NormalTok{ \{}
        \KeywordTok{case} \FunctionTok{Sum}\NormalTok{(l, r) => }\FunctionTok{eval}\NormalTok{(l, env) + }\FunctionTok{eval}\NormalTok{(r, env) }
        \KeywordTok{case} \FunctionTok{Var}\NormalTok{(n)    => }\FunctionTok{env}\NormalTok{(n) }
        \KeywordTok{case} \FunctionTok{Const}\NormalTok{(v)  => v }
\NormalTok{    \}}
\end{Highlighting}
\end{Shaded}

This evaluation function performs \emph{pattern matching} on the tree
\texttt{t} (i.e., using the \texttt{match} operator).

\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\item
  The pattern match first checks whether the tree \texttt{t} is a
  \texttt{Sum} object (i.e., an instance of the \texttt{Sum} case
  class).

  If the tree is a \texttt{Sum}, the pattern match binds the left
  subtree to a new variable \texttt{l} and the right subtree to a new
  variable \texttt{r}, then evaluates the expression following the arrow
  \texttt{=\textgreater{}}.

  This expression uses the values of the variables bound by the pattern
  match, i.e., \texttt{l} and \texttt{r} in the \texttt{Sum} case.
\item
  If the first check does not succeed, that is, the tree is not a
  \texttt{Sum} object, the pattern match then checks whether \texttt{t}
  is a \texttt{Var} object.

  If the tree is a \texttt{Var}, the pattern match binds the name
  contained in the \texttt{Var} node to a new variable \texttt{n} and
  then evaluates the right-hand-side expression.
\item
  If the second check also fails, that is, if \texttt{t} is neither a
  \texttt{Sum} nor a \texttt{Var}, the pattern match then checks whether
  the expression is a \texttt{Const} object.

  If the tree is a \texttt{Const}, the pattern match binds the value
  contained in the \texttt{Const} node to a new variable \texttt{v} and
  then evaluates the right-hand-side expression.
\item
  Finally, if all checks fail, the pattern match expression raises an
  exception to signal failure. In this version of \texttt{eval}, failure
  occurs only when there are additional subclasses of \texttt{Tree} that
  we have declared but not yet defined in the \texttt{eval} pattern
  match.
\end{enumerate}

Pattern matching attempts to match a value to a series of patterns. As
soon as a pattern matches (moving top to bottom, left to right in the
source code), the program extracts and names various parts of the value
and then evaluates the associated expression using the values of these
named parts.

An object-oriented programmer might ask why we did not define
\texttt{eval} as a \emph{method} of class \texttt{Tree} and its
subclasses.

We could do that, because Scala allows method definitions in case
classes just as in normal classes.

Deciding whether to use pattern matching or methods is partly a matter
of taste. But the choice also affects the extensibility the program.

\begin{itemize}
\item
  Using methods, we can easily add a new kind of node by defining a new
  subclass of \texttt{Tree}. But adding a new operation to manipulate
  the tree is tedious because it requires us to modify every subclass of
  \texttt{Tree}.
\item
  Using pattern matching, the situation is reversed: adding a new kind
  of node requires us to modify all functions that do pattern matching
  on the tree, to take the new node into account. But adding a new
  operation is easy, we just define it as an independent function.
\end{itemize}

To explore pattern matching further, consider another operation on
arithmetic expressions: symbolic derivation. Looking back at our
calculus class, we see the following rules for differentiation:

\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\item
  The derivative of a sum is the sum of the derivatives.
\item
  The derivative of some variable \texttt{v} is 1 if \texttt{v} is the
  variable relative to which the derivation takes place, and is 0
  otherwise.
\item
  The derivative of a constant is 0.
\end{enumerate}

We can directly translate these rules into a Scala function that uses
the above case classes and pattern matching, as follows:

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{def} \FunctionTok{derive}\NormalTok{(t: Tree, v: String): Tree = t }\KeywordTok{match}\NormalTok{ \{}
        \KeywordTok{case} \FunctionTok{Sum}\NormalTok{(l, r)          => }\FunctionTok{Sum}\NormalTok{(}\FunctionTok{derive}\NormalTok{(l, v), }\FunctionTok{derive}\NormalTok{(r, v))}
        \KeywordTok{case} \FunctionTok{Var}\NormalTok{(n) }\KeywordTok{if}\NormalTok{ (v == n) => }\FunctionTok{Const}\NormalTok{(}\DecValTok{1}\NormalTok{)}
        \KeywordTok{case}\NormalTok{ _                  => }\FunctionTok{Const}\NormalTok{(}\DecValTok{0}\NormalTok{)}
\NormalTok{    \}}
\end{Highlighting}
\end{Shaded}

Function \texttt{derive} introduces two new concepts related to pattern
matching.

\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\item
  The \texttt{case} expression for variables has a \emph{guard}, an
  expression following the \texttt{if} keyword. This guard prevents
  pattern matching from succeeding unless its expression is true.

  Here the guard ensures that the function returns the constant
  \texttt{1} only if the name of the variable being derived is the same
  as the derivation variable \texttt{v}.
\item
  A pattern can include a \emph{wildcard}, written \texttt{\_}, that
  matches any value, without giving it a name.
\end{enumerate}

Consider an example with a simple \texttt{main} function that performs
several operations on the expression \texttt{(x+x)+(7+y)}.

It first computes its value in the environment
\texttt{\{\ x\ -\textgreater{}\ 5,\ y\ -\textgreater{}\ 7\ \}} and then
computes its derivative relative to \texttt{x} and then to \texttt{y}.

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{def} \FunctionTok{main}\NormalTok{(args: Array[String]) \{}
        \KeywordTok{val}\NormalTok{ exp: Tree = }\FunctionTok{Sum}\NormalTok{(}\FunctionTok{Sum}\NormalTok{(}\FunctionTok{Var}\NormalTok{(}\StringTok{"x"}\NormalTok{),}\FunctionTok{Var}\NormalTok{(}\StringTok{"x"}\NormalTok{)),}\FunctionTok{Sum}\NormalTok{(}\FunctionTok{Const}\NormalTok{(}\DecValTok{7}\NormalTok{),}\FunctionTok{Var}\NormalTok{(}\StringTok{"y"}\NormalTok{)))}
        \KeywordTok{val}\NormalTok{ env: Environment = \{ }\KeywordTok{case} \StringTok{"x"}\NormalTok{ => }\DecValTok{5} \KeywordTok{case} \StringTok{"y"}\NormalTok{ => }\DecValTok{7}\NormalTok{ \}}
        \FunctionTok{println}\NormalTok{(}\StringTok{"Expression: "}\NormalTok{ + exp)}
        \FunctionTok{println}\NormalTok{(}\StringTok{"Evaluation with x=5, y=7: "}\NormalTok{ + }\FunctionTok{eval}\NormalTok{(exp, env))}
        \FunctionTok{println}\NormalTok{(}\StringTok{"Derivative relative to x:}\CharTok{\textbackslash{}n}\StringTok{ "}\NormalTok{ + }\FunctionTok{derive}\NormalTok{(exp, }\StringTok{"x"}\NormalTok{))}
        \FunctionTok{println}\NormalTok{(}\StringTok{"Derivative relative to y:}\CharTok{\textbackslash{}n}\StringTok{ "}\NormalTok{ + }\FunctionTok{derive}\NormalTok{(exp, }\StringTok{"y"}\NormalTok{))}
\NormalTok{    \}}
\end{Highlighting}
\end{Shaded}

Executing this program, we get the expected output:

\begin{verbatim}
    Expression: Sum(Sum(Var(x),Var(x)),Sum(Const(7),Var(y)))
    Evaluation with x=5, y=7: 24
    Derivative relative to x:
    Sum(Sum(Const(1),Const(1)),Sum(Const(0),Const(0)))
    Derivative relative to y:
    Sum(Sum(Const(0),Const(0)),Sum(Const(0),Const(1)))
\end{verbatim}

The result of the derivative is complex. It should be simplified before
printing. Defining a basic simplification function using pattern
matching is an interesting (but surprisingly tricky) problem, left as an
exercise for the reader.

\hypertarget{expression-tree-code}{%
\subsubsection{Expression Tree Code}\label{expression-tree-code}}

The Scala source code for the case class version of the Expression Tree
program is in file \href{ExprCase.scala}{\texttt{ExprCase.scala}}.

A traditional object-oriented version of the Expression Tree program is
in file \href{ExprObj.scala}{\texttt{ExprObj.scala}}.

\hypertarget{traits}{%
\subsection{Traits}\label{traits}}

In addition to inheriting code from a superclass, a Scala class can also
reuse code from one or several \emph{traits}.

From a Java perpective, traits can be viewed as interfaces that can also
contain code. In Scala, when a class inherits from a trait, it
implements that trait's interface, and inherits all the code contained
in the trait.

Note: In older Java implementations, an interface consisted of just
method signatures and constants. In Java 8, interfaces can now include
default definitions of methods, somewhat similar to Scala traits.

To see the usefulness of traits, consider a classic example: ordered
objects. We want to compare objects of a given class among themselves.
For example, we need to compare objects according to some total order to
sort them.

In Java, objects that can be compared implement the \texttt{Comparable}
interface.

In Scala, we can do better by defining the equivalent of
\texttt{Comparable} as a trait, which we call \texttt{Ord}.

When comparing objects, six different comparison operations are useful:
smaller, smaller or equal, equal, not equal, greater or equal, and
greater.

But it is tedious to define all of these for every class whose instances
we wish to compare.

We observe that we can define four of the six in terms of the other two.
For example, given the equal and smaller comparison operators, we can
define the other four comparison operators.

In Scala, we can capture this observation in the following trait
declaration:

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{trait}\NormalTok{ Ord \{}
        \KeywordTok{def}\NormalTok{ < (that: Any): Boolean}
        \KeywordTok{def}\NormalTok{ <=(that: Any): Boolean =  (}\KeywordTok{this}\NormalTok{ < that) || (}\KeywordTok{this}\NormalTok{ == that)}
        \KeywordTok{def}\NormalTok{ > (that: Any): Boolean = !(}\KeywordTok{this}\NormalTok{ <= that)}
        \KeywordTok{def}\NormalTok{ >=(that: Any): Boolean = !(}\KeywordTok{this}\NormalTok{ < that)}
\NormalTok{    \}}
\end{Highlighting}
\end{Shaded}

This definition both creates a new type called \texttt{Ord}, which plays
the same role as Java's \texttt{Comparable} interface, and generates
default implementations of three comparison operators in terms of a
fourth, abstract operator. All classes inherit the equality and
inequality operators and, thus, those operators do not need to be
defined in \texttt{Ord}.

The type \texttt{Any} used above, is the supertype of all other types in
Scala. It is essentially a more general version of Java's
\texttt{Object} type that is also a supertype of basic types like
\texttt{Int}, \texttt{Float}, etc.

To make objects of a class comparable, it is sufficient to define
equality and inferiority operators and then ``mix in'' the \texttt{Ord}
trait.

For example, consider a \texttt{Date} class representing dates in the
Gregorian calendar. Such dates are composed of a day, a month, and a
year, each of which we can represent with an integer. We can start the
definition of the \texttt{Date} class as follows:

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{class}\NormalTok{ Date(y: Int, m: Int, d: Int) }\KeywordTok{extends}\NormalTok{ Ord \{}
        \KeywordTok{def}\NormalTok{ year  = y}
        \KeywordTok{def}\NormalTok{ month = m}
        \KeywordTok{def}\NormalTok{ day   = d}
        \KeywordTok{override} \KeywordTok{def} \FunctionTok{toString}\NormalTok{(): String = year + }\StringTok{"-"}\NormalTok{ + month + }\StringTok{"-"}\NormalTok{ + day}
        \CommentTok{// ... two methods defined below}
\NormalTok{    \}}
\end{Highlighting}
\end{Shaded}

The \texttt{extends\ Ord} declaration specifies that the \texttt{Date}
class inherits from the \texttt{Ord} trait (in addition to the default
superclass).

To make the comparisons work correctly, we redefine the \texttt{equals}
method, inherited from Java's \texttt{Object} class, to compare dates by
comparing their individual fields. The default implementation of
\texttt{equals} does not work because it compares objects physically. In
Scala, the comparison becomes:

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{override} \KeywordTok{def} \FunctionTok{equals}\NormalTok{(that: Any): Boolean =}
\NormalTok{        that.}\FunctionTok{isInstanceOf}\NormalTok{[Date] && \{}
            \KeywordTok{val}\NormalTok{ o = that.}\FunctionTok{asInstanceOf}\NormalTok{[Date]}
\NormalTok{            o.}\FunctionTok{day}\NormalTok{ == day && o.}\FunctionTok{month}\NormalTok{ == month && o.}\FunctionTok{year}\NormalTok{ == year}
\NormalTok{        \}}
\end{Highlighting}
\end{Shaded}

This method uses the predefined methods \texttt{isInstanceOf} and
\texttt{asInstanceOf}.

\begin{itemize}
\item
  \texttt{isInstanceOf} corresponds to the Java \texttt{instanceof}
  operator. It returns true if and only if the object to which it is
  applied is an instance of the given type.
\item
  \texttt{asInstanceOf} corresponds to the Java cast operator: if the
  object is an instance of the given type, it is viewed as such,
  otherwise it throws a \texttt{ClassCastException}.
\end{itemize}

To complete our implementation, we need to define the
\texttt{\textless{}} operator. It uses the predefined Scala method
\texttt{error} to throw an exception with the given error message.

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{def}\NormalTok{ <(that: Any): Boolean = \{}
        \KeywordTok{if}\NormalTok{ (!that.}\FunctionTok{isInstanceOf}\NormalTok{[Date])}
            \FunctionTok{error}\NormalTok{(}\StringTok{"cannot compare "}\NormalTok{ + that + }\StringTok{" and a Date"}\NormalTok{)}

        \KeywordTok{val}\NormalTok{ o = that.}\FunctionTok{asInstanceOf}\NormalTok{[Date]}
\NormalTok{        (year < o.}\FunctionTok{year}\NormalTok{) ||}
\NormalTok{        (year == o.}\FunctionTok{year}\NormalTok{ && (month < o.}\FunctionTok{month}\NormalTok{ ||}
\NormalTok{                           (month == o.}\FunctionTok{month}\NormalTok{ && day < o.}\FunctionTok{day}\NormalTok{)))}
\NormalTok{    \}}
\end{Highlighting}
\end{Shaded}

This completes the definition of the \texttt{Date} class.

Instances of the \texttt{Date} class can be seen either as dates or as
comparable objects. They define all six comparison operators:

\begin{itemize}
\item
  \texttt{equals} and \texttt{\textless{}} because they appear directly
  in the definition of the \texttt{Date} class
\item
  the other four because they are inherited from the \texttt{Ord} trait
\end{itemize}

Traits are useful in many other situations, as you will see as you
program more in Scala.

\hypertarget{genericity}{%
\subsection{Genericity}\label{genericity}}

Scala supports generics. Java did not support generics until Java 5.

\emph{Genericity} is the ability to write code parameterized by types.

For example, suppose we are writing a library for linked lists. What
type do we give the elements of the list?

\begin{itemize}
\item
  If we choose a specific concrete type such as \texttt{Int}, we
  severely limit the usefulness of the library. It is impractical to
  include different implementation for every possible concrete type.
\item
  If follow choose a default supertype like \texttt{Any}, then users of
  our library would need to their lace code with many type checks and
  type casts. (In Java, there was also the problem that basic types do
  not inherit from \texttt{Object}.)
\end{itemize}

Scala supports generic classes and methods to solve this problem. As an
example, consider the simplest possible container class: a reference,
which can either be empty or point to an object of some type.

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{class}\NormalTok{ Reference[T] \{}
        \KeywordTok{private} \KeywordTok{var}\NormalTok{ contents: T = _}
        \KeywordTok{def} \FunctionTok{set}\NormalTok{(value: T) \{ contents = value \}}
        \KeywordTok{def}\NormalTok{ get: T = contents}
\NormalTok{    \}}
\end{Highlighting}
\end{Shaded}

This example parameterizes the class \texttt{Reference} with a type
\texttt{T}, which is the type of its element. The body of the class
declares the \texttt{contents} variable, the argument of the
\texttt{set} method, and the return type of the \texttt{get} method to
have type `T'.

This is our first example to use mutable variables declare with
\texttt{var}. In this example, we initialize the \texttt{contents}
variable to have the value \texttt{\_}, which represents the default
value for the type. This default value is 0 for numeric types,
\texttt{false} for the \texttt{Boolean} type, \texttt{()} for the
\texttt{Unit} type, and \texttt{null} for all object types.

To use this \texttt{Reference} class, we need to specify what type to
use for the type parameter \texttt{T}, that is, the type of the element
contained in the cell. For example, to create and use a cell holding an
integer, one could write the following:

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{object}\NormalTok{ IntegerReference \{}
        \KeywordTok{def} \FunctionTok{main}\NormalTok{(args: Array[String]) \{}
            \KeywordTok{val}\NormalTok{ cell = }\KeywordTok{new}\NormalTok{ Reference[Int]}
\NormalTok{            cell.}\FunctionTok{set}\NormalTok{(}\DecValTok{13}\NormalTok{)}
            \FunctionTok{println}\NormalTok{(}\StringTok{"Reference contains the half of "}\NormalTok{ + (cell.}\FunctionTok{get}\NormalTok{ * }\DecValTok{2}\NormalTok{))}
\NormalTok{        \}}
\NormalTok{    \}}
\end{Highlighting}
\end{Shaded}

This example does not need to cast the value returned by the
\texttt{get} method before using it as an integer. It is also not
possible to store anything but an integer in that particular cell,
because it was declared as holding an integer.

\hypertarget{conclusion}{%
\subsection{Conclusion}\label{conclusion}}

The goal of this document is to provide a quick overview of Scala for
programmers already familiar with Java. To learn more, use a textbook,
reference book, other tutorials, and manuals.

\hypertarget{exercises}{%
\subsection{Exercises}\label{exercises}}

TODO: More exercises

\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\item
  Extend the \href{ExprCase.scala}{case class version of the
  expression-tree calculator program} as described below.

  \begin{enumerate}
  \def\labelenumii{\alph{enumii}.}
  \item
    Modify the \texttt{Tree} algebraic data type as follows:

    \begin{itemize}
    \item
      Change node type \texttt{Const} to represent a floating point
      number instead of an integer.
    \item
      Add node types \texttt{Sub}, \texttt{Prod}, and \texttt{Div} to
      represent subtraction, multiplication, and division of the two
      values, respectively. (Assume \texttt{Sub} means that the right
      operand is subtracted from the left operand.)
    \item
      add node type \texttt{Neg} to represent negating a value.
    \item
      add node types \texttt{Sin} and \texttt{Cos} to represent the sine
      and cosine trigonometric functions, respectively.
    \end{itemize}
  \item
    Extend functions \texttt{eval} and \texttt{derive} to support the
    above modifications of \texttt{Tree}. Test the extended functions
    thoroughly. (What should be done for division by zero?)
  \end{enumerate}
\item
  Further extend the expression \texttt{Tree} program developed in the
  previous exercise as described below.

  \begin{enumerate}
  \def\labelenumii{\alph{enumii}.}
  \item
    Develop a new function \texttt{simplify} that takes an extended
    expression \texttt{Tree}, simplifies it by evaluating \emph{all}
    subexpressions involving only constants (i.e., not evaluating
    variables), and returns the new expression \texttt{Tree}.

    For example:

    \begin{itemize}
    \tightlist
    \item
      \texttt{simplify(Add(Const(2),Const(3)))} yields \texttt{Const(5)}
    \item
      \texttt{simplify(Add(Add(Const(1),Const(1)),Mul(Const(1),Const(3))))}
      yields \texttt{Const(5)}.
    \item
      \texttt{simplify(Neg(Const(5)))} yields \texttt{Const(-5)}
    \end{itemize}
  \item
    Extend the \texttt{simplify} function to exploit mathematical
    properties such as identity elements
    (\texttt{x\ +\ 0\ =\ x\ =\ 0\ +\ x}), and zeros
  \item
    Further extend the \texttt{simplify} function to exploit
    associativity (\texttt{(x\ +\ y)\ +\ z\ =\ x\ +\ (y\ +\ z)},
    commutativity (\texttt{x\ +\ 1\ =\ 1\ +\ x}), etc.
  \end{enumerate}
\item
  Modify and extend the \href{ExprObj.scala}{traditional object-oriented
  version of the expression-tree calculator program} in the same manner
  as described in the previous two exercises.
\end{enumerate}

\hypertarget{acknowledgements}{%
\subsection{Acknowledgements}\label{acknowledgements}}

In February 2016, I created these notes by adapting and expanding the
web document ``A Scala Tutorial for Java Programmers'' by Michel Schinz
and Phillipp Haller to better meet the needs of my Scala-based course
(to explain some items more thoroughly, improve the narrative, and make
the document accessible). The original document can be found on the
Scala Language website at
\url{http://docs.scala-lang.org/tutorials/scala-for-java-programmers.html}.

In Spring 2017, I updated the format to be better compatible with
Pandoc. I revised the document further in Spring 2018 (e.g., adding the
first exercises).

I maintain these notes as text in Pandoc's dialect of Markdown using
embedded LaTeX markup for the mathematical formulas and then translate
the notes to HTML, PDF, and other forms as needed.

\hypertarget{references}{%
\subsection{References}\label{references}}

TODO: Add

\hypertarget{concepts}{%
\subsection{Concepts}\label{concepts}}

TODO: Add

\end{document}
