\PassOptionsToPackage{unicode=true}{hyperref} % options for packages loaded elsewhere
\PassOptionsToPackage{hyphens}{url}
%
\documentclass[english,]{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 555: Functional Programming 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}
\ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex
  \usepackage[shorthands=off,main=english]{babel}
\else
  % load polyglossia as late as possible as it *could* call bidi if RTL lang (e.g. Hebrew or Arabic)
  \usepackage{polyglossia}
  \setmainlanguage[]{english}
\fi

\title{CSci 555: Functional Programming\\
Notes on Scala for Java Programmers}
\author{\textbf{H. Conrad Cunningham}}
\date{\textbf{7 February 2019}}

\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{Note:} In Spring 2016, I created these notes by adapting and
expanding the Web document ``A Scala Tutorial for Java Programmers'' by
Michel Schinz and Phillipp Haller from the Scala language website:

\url{http://docs.scala-lang.org/tutorials/scala-for-java-programmers.html}

I sought to explain some items more thoroughly for my students, improve
the narrative, and make the document accessible. See the
Acknowledgements section for more information.

\textbf{Browser Advisory:} The HTML version of this textbook requires a
browser that supports the display of MathML. A good choice as of
February 2019 is a recent version of Firefox from Mozilla.

\newpage

\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 an
introductory computer science course sequence using Java---such as the
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 (e.g.~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
\VERB|\NormalTok{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}

Note: The Scala source code for the \VERB|\NormalTok{HelloWorld}|
program is in file
\href{HelloWorld.scala}{\VERB|\ExtensionTok{HelloWorld.scala}|}.

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

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

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

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

\begin{Shaded}
\begin{Highlighting}[]
    \OperatorTok{>} \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 \VERB|\ExtensionTok{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 \VERB|\ExtensionTok{scala}| command (similar to the
\VERB|\ExtensionTok{java}| command) to execute the
\VERB|\NormalTok{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
\VERB|\NormalTok{java.}\FunctionTok{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}

Note: The Scala source code for the \VERB|\NormalTok{FrenchDate}|
program is in file
\href{FrenchDate.scala}{\VERB|\ExtensionTok{FrenchDate.scala}|}. The
source file \href{MoreDates.scala}{\texttt{MoreDates.scala}} expands the
\VERB|\NormalTok{FrenchDate}| program to include Chinese, Portuguese,
Hebrew, and Arabic date formats.

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

The Scala \VERB|\KeywordTok{import}| statement is more powerful than
Java's.

\begin{itemize}
\item
  It can import multiple classes by enclosing names in braces.

  The first line above imports the \VERB|\BuiltInTok{Data}| and
  \VERB|\BuiltInTok{Locale}| classes from Java package
  \VERB|\NormalTok{java.}\FunctionTok{util}|.
\item
  It can import everything in a package or class by using an underscore
  character (\VERB|\NormalTok{_}|) instead of a Java's asterisk
  (\VERB|\NormalTok{*}|).

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

The \VERB|\NormalTok{main}| method in the \VERB|\NormalTok{FrenchDate}|
object:

\begin{itemize}
\item
  creates an instance of Java's \VERB|\BuiltInTok{Date}| class, thus
  getting the current date
\item
  uses the imported static method \VERB|\NormalTok{getDateInstance}| to
  format the date appropriately for France using
  \VERB|\BuiltInTok{Locale}\NormalTok{.}\FunctionTok{France}|
\item
  prints the current date formatted according to the localized
  \VERB|\BuiltInTok{DateFormat}| instance
\end{itemize}

The \VERB|\NormalTok{main}| method declares two local ``variables'' in
its body: \VERB|\NormalTok{now}| and \VERB|\NormalTok{df}|.*

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

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

  Although we cannot change the binding of a \VERB|\KeywordTok{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
  \href{https://en.wikipedia.org/wiki/Type_inference}{\emph{inferred}}
  by the compiler from the type of the initializing expression.
\end{itemize}

\begin{description}
\item[Programming guideline:]
Declare a Scala variable with \VERB|\KeywordTok{val}| by default. Only
change the declaration to \VERB|\KeywordTok{var}| if you explicitly
decide to allow the variable binding to change.
\end{description}

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
\emph{object}, including numbers and functions.

Scala does not distinguish the Java primitive types
(e.g.~\VERB|\NormalTok{Boolean}| and \VERB|\NormalTok{Int}|) from
reference types (e.g.~objects). It enables us to manipulate functions as
\emph{first-class} values.

Note: For more details on objects, classes, and the object-oriented
paradigms, see the
\href{https://john.cs.olemiss.edu/~hcc/csci450/ELIFP/Ch03/03_Object_Paradigms.html\#object-model}{Object
Model} section of the
\href{https://john.cs.olemiss.edu/~hcc/csci450/ELIFP/Ch03/03_Object_Paradigms.html}{Object-Based
Paradigms} chapter of the textbook
\href{https://john.cs.olemiss.edu/~hcc/csci450/ELIFP/ExploringLanguages.html\#exploring-languages-with-interpreters-and-functional-programming}{Exploring
Languages with Interpreters and Functional Programming} {[}Cunningham
2018{]}.

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

Since numbers are objects, they also have \emph{methods}
(i.e.~operations). 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.~\VERB|\NormalTok{+}|,
\VERB|\NormalTok{*}|, \VERB|\NormalTok{/}|) 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 \VERB|\NormalTok{Double}|.

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

Because Scala functions are objects, we can:

\begin{itemize}
\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.
\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.
\end{itemize}

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

Consider the \VERB|\NormalTok{Timer}| program below. It includes a timer
function named \VERB|\NormalTok{oncePerSecond}| that performs some
action every second. The specific action performed is encoded as a
\emph{call-back} function passed into \VERB|\NormalTok{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}

Note: The Scala source code for the \VERB|\NormalTok{Timer}| program is
in file \href{Timer.scala}{\VERB|\ExtensionTok{Timer.scala}|}.

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

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

The \VERB|\NormalTok{main}| function calls this timer function, passing
a call-back function that prints the string

\begin{verbatim}
    time flies like an arrow...
\end{verbatim}

on the console. The program endlessly prints this string every second.

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

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

The \VERB|\NormalTok{Timer}| program in the subsection above can be
refined by replacing the function \VERB|\NormalTok{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}

Note: The Scala source code for the \VERB|\NormalTok{TimerAnonymous}|
program is in file
\href{TimerAnonymous.scala}{\VERB|\ExtensionTok{TimerAnonymous.scala}|}.

In the anonymous function, a right arrow \VERB|\NormalTok{=>}| 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 \emph{class-based language}. However, Scala
classes can have parameters. Consider the following class
\VERB|\NormalTok{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 \VERB|\NormalTok{Complex}| class takes two arguments, the real and
imaginary parts of the complex number. In the \VERB|\NormalTok{Complex}|
class, these become \VERB|\KeywordTok{val}| fields of the object
(i.e.~class instance) that are only visible and accessible from
\emph{inside the object}. (This visibility is
\VERB|\KeywordTok{private}\NormalTok{[}\KeywordTok{this}\NormalTok{]}|,
a type of visibility that does not occur in Java.)

The default constructor is built into the \VERB|\KeywordTok{class}|
syntax. We pass values for these arguments when we create an instance of
class \VERB|\NormalTok{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 \VERB|\NormalTok{Complex}| class defines function methods
\VERB|\NormalTok{re}| and \VERB|\NormalTok{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 \VERB|\NormalTok{=}| 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 \VERB|\NormalTok{Complex}|, the compiler infers the return types for
methods \VERB|\FunctionTok{re}\NormalTok{()}| and
\VERB|\FunctionTok{im}\NormalTok{()}| by examining the right-hand sides
and deducing that both return a value of type \VERB|\NormalTok{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, the author of these notes considers it better software
engineering practice to explicitly specify the types of all
\emph{public} features of a class or package such as the
\VERB|\FunctionTok{re}\NormalTok{()}| and
\VERB|\FunctionTok{im}\NormalTok{()}| 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 \VERB|\NormalTok{now}| and \VERB|\NormalTok{df}| values in the
\VERB|\NormalTok{FrenchDate}| object shown in a previous section.

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

To call the methods \VERB|\NormalTok{re}| and \VERB|\NormalTok{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{(s}\StringTok{"imaginary part:  $\{c.im()\}"}\NormalTok{) }
\NormalTok{        \}}
\NormalTok{    \}}
\end{Highlighting}
\end{Shaded}

In this example, we pass an \emph{interpolated string} as the argument
to \VERB|\NormalTok{println}|. The feature

\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{    s}\StringTok{"imaginary part:  $\{c.im()\}"}
\end{Highlighting}
\end{Shaded}

denotes a string with the value of the expression
\VERB|\NormalTok{c.}\FunctionTok{im}\NormalTok{()}|, converted to a
string using \VERB|\NormalTok{toString}|, and inserted in place of the
term \VERB|\NormalTok{$\{c.}\FunctionTok{im}\NormalTok{()\}}|.

We can eliminate the empty parameter list by defining
\VERB|\NormalTok{re}| and \VERB|\NormalTok{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 \emph{superclass}. If no super class
is given explicitly, then the superclass is
\VERB|\NormalTok{scala.}\FunctionTok{AnyRef}| by default.

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

Like Java, a Scala class may \emph{override} individual methods by
giving new definitions.

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

For example, the \VERB|\NormalTok{Complex}| class can redefine the
\VERB|\NormalTok{toString}| method inherited from
\VERB|\NormalTok{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{() =}
\NormalTok{            s}\StringTok{"$\{re\}$\{(if (im < 0) "" else "}\NormalTok{+}\StringTok{")\}$\{im\}i"}
\NormalTok{    \}}
\end{Highlighting}
\end{Shaded}

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

Note: The Scala source code for \VERB|\NormalTok{ComplexNumbers}|
programs using the three different definitions of class
\VERB|\NormalTok{Complex}| are in files
\href{ComplexNumbers.scala}{\VERB|\ExtensionTok{ComplexNumbers.scala}|},
\href{ComplexNumbers2.scala}{\VERB|\ExtensionTok{ComplexNumbers2.scala}|},
and
\href{ComplexNumbers3.scala}{\VERB|\ExtensionTok{ComplexNumbers3.scala}|}.

\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
\VERB|\DecValTok{1}\NormalTok{+}\DecValTok{2}| and
\VERB|\NormalTok{(x+x)+(}\DecValTok{7}\NormalTok{+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 \VERB|\NormalTok{Sum}|, \VERB|\NormalTok{Var}| and
\VERB|\NormalTok{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
  \VERB|\KeywordTok{new}| keyword, for example, we can write
  \VERB|\FunctionTok{Const}\NormalTok{(}\DecValTok{5}\NormalTok{)}|
  instead of
  \VERB|\KeywordTok{new} \FunctionTok{Const}\NormalTok{(}\DecValTok{5}\NormalTok{)}|.
\item
  The compiler automatically generates getter functions for the
  constructor parameters. That is, it is possible to get the value of
  the \VERB|\NormalTok{v}| constructor parameter of some instance
  \VERB|\NormalTok{c}| of class \VERB|\NormalTok{Const}| just by writing
  \VERB|\NormalTok{c.}\FunctionTok{v}|.
\item
  The compiler supplies default definitions for the methods
  \VERB|\NormalTok{equals}| and \VERB|\NormalTok{hashCode}|. These work
  on the \emph{structure} of the instances and not on their identities.
\item
  The compiler provides a default definition for method
  \VERB|\NormalTok{toString}|, which prints the value in a ``source''
  form. For example, the tree for expression
  \VERB|\NormalTok{x+}\DecValTok{1}| prints as
  \VERB|\FunctionTok{Sum}\NormalTok{(}\FunctionTok{Var}\NormalTok{(x),}\FunctionTok{Const}\NormalTok{(}\DecValTok{1}\NormalTok{))}|.
\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 the algebraic data types in a functional language such as Haskell.

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
\VERB|\DecValTok{6}| as result.

An environment is just a function that associates a value with a
(variable) name. The environment
\VERB|\NormalTok{\{ x -> }\DecValTok{5}\NormalTok{ \}}| 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
\VERB|\StringTok{"x"}| as argument, returns the integer
\VERB|\DecValTok{5}|, and, otherwise, fails and throws an exception.

An environment is a function of type \VERB|\NormalTok{String => Int}|.
To simplify our evaluation program, we define the name
\VERB|\NormalTok{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
\VERB|\NormalTok{t}| (i.e.~using the \VERB|\KeywordTok{match}|
operator).

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

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

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

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

  If the tree is a \VERB|\NormalTok{Const}|, the pattern match binds the
  value contained in the \texttt{Const} node to a new variable
  \VERB|\NormalTok{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
  \VERB|\NormalTok{eval}|, failure occurs only when there are additional
  subclasses of \VERB|\NormalTok{Tree}| that we have declared but not
  yet defined in the \VERB|\NormalTok{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
\VERB|\NormalTok{eval}| as a \emph{method} of class
\VERB|\NormalTok{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 \VERB|\NormalTok{Tree}|. But adding a new operation to
  manipulate the tree is tedious because it requires us to modify every
  subclass of \VERB|\NormalTok{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 \VERB|\NormalTok{v}| is 1 if
  \VERB|\NormalTok{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 \VERB|\NormalTok{derive}| introduces two new concepts related
to pattern matching.

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

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

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

It first computes its value in the environment

\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{    \{ x -> }\DecValTok{5}\NormalTok{, y -> }\DecValTok{7}\NormalTok{ \}}
\end{Highlighting}
\end{Shaded}

and then computes its derivative relative to \VERB|\NormalTok{x}| and
then to \VERB|\NormalTok{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}{\VERB|\ExtensionTok{ExprCase.scala}|}.

A traditional object-oriented version of the Expression Tree program is
in file \href{ExprObj.scala}{\VERB|\ExtensionTok{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 versions, 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.

\hypertarget{ordered-objects-example}{%
\subsubsection{Ordered objects example}\label{ordered-objects-example}}

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
\VERB|\BuiltInTok{Comparable}| interface.

In Scala, we can do better by defining the equivalent of
\VERB|\NormalTok{Comparable}| as a trait, which we call
\VERB|\NormalTok{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 \VERB|\NormalTok{Ord}|,
which plays the same role as Java's \VERB|\NormalTok{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 \VERB|\NormalTok{Ord}|.

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

Note: See discussion of Scala's
\href{https://docs.scala-lang.org/tour/unified-types.html}{unified
types} for more information on the type hierarchy.

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

For example, consider a \VERB|\NormalTok{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 \VERB|\NormalTok{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 = s}\StringTok{"$year-$month-$day"}
        \CommentTok{// ... equals methods defined below}
\NormalTok{    \}}
\end{Highlighting}
\end{Shaded}

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

To make the comparisons work correctly, we redefine the
\VERB|\NormalTok{equals}| method, inherited from Java's
\VERB|\NormalTok{Object}| class, to compare dates by comparing their
individual fields. The default implementation of
\VERB|\NormalTok{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}

\hypertarget{aside-on-equality}{%
\subsubsection{Aside on equality}\label{aside-on-equality}}

Scala defines method \VERB|\NormalTok{equals}| in the top-level class
\VERB|\NormalTok{Any}|. The comparison
\VERB|\NormalTok{x.}\FunctionTok{equals}\NormalTok{(y)}| yields
\VERB|\KeywordTok{true}| if and only if the values of
\VERB|\NormalTok{x}| and \VERB|\NormalTok{y}| are equivalent. Method
\VERB|\NormalTok{equals}| can be overriden in a subclass. Thus, when we
redefine \VERB|\NormalTok{equals}|, we must ensure that the new
definition is an \emph{equivalence relation}. That is, it should be:

\begin{itemize}
\tightlist
\item
  \emph{reflexive}
  (\VERB|\NormalTok{x.}\FunctionTok{equals}\NormalTok{(x)}|)
\item
  \emph{symmetric}
  (\VERB|\NormalTok{x.}\FunctionTok{equals}\NormalTok{(y)}| equals
  \VERB|\NormalTok{y.}\FunctionTok{equals}\NormalTok{(x)}|)
\item
  \emph{transitive} (if
  \VERB|\NormalTok{x.}\FunctionTok{equals}\NormalTok{(y)}| and
  \VERB|\NormalTok{y.}\FunctionTok{equals}\NormalTok{(z)}|, then
  \VERB|\NormalTok{x.}\FunctionTok{equals}\NormalTok{(z)}|)
\end{itemize}

Scala defines method \VERB|\NormalTok{eq}| in the class
\VERB|\NormalTok{AnyRef}|, which is the top-level class for
\emph{reference objects}, but a subclass of \VERB|\NormalTok{Any}|. The
comparison \VERB|\NormalTok{x.}\FunctionTok{eq}\NormalTok{(y)}| yields
\VERB|\KeywordTok{true}| if and only if \VERB|\NormalTok{x}| and
\VERB|\NormalTok{y}| are identical references (pointers). That is,
\VERB|\NormalTok{x}| and \VERB|\NormalTok{y}| denote the same physical
object.

By default, Scala defines \VERB|\NormalTok{equals}| to be the same as
\VERB|\NormalTok{eq}|.

Unlike Java, Scala defines \VERB|\NormalTok{x == y}| equivalent to

\begin{Shaded}
\begin{Highlighting}[]
    \KeywordTok{if}\NormalTok{ (x eq }\KeywordTok{null}\NormalTok{) }\CommentTok{// i.e. x.eq(null)}
\NormalTok{        y eq }\KeywordTok{null}
    \KeywordTok{else}
\NormalTok{        x equals y }\CommentTok{// i.e. x.equals(y)}
\end{Highlighting}
\end{Shaded}

and defines \VERB|\NormalTok{x != y}| equivalent to
\VERB|\NormalTok{!(x == y)}|.

Thus, by redefining \VERB|\NormalTok{equals}|, we redefine
\VERB|\NormalTok{==}| and \VERB|\NormalTok{!=}| as well.

\hypertarget{ordered-objects-continued}{%
\subsubsection{Ordered objects
continued}\label{ordered-objects-continued}}

The redefined \VERB|\NormalTok{equals}| method for the
\VERB|\NormalTok{Date}| class above uses the predefined methods
\VERB|\NormalTok{isInstanceOf}| and \VERB|\NormalTok{asInstanceOf}|.

\begin{itemize}
\item
  \VERB|\NormalTok{isInstanceOf}| corresponds to the Java
  \VERB|\NormalTok{instanceof}| operator. It returns true if and only if
  the object to which it is applied is an instance of the given type.
\item
  \VERB|\NormalTok{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 \VERB|\NormalTok{ClassCastException}|.
\end{itemize}

To complete our implementation, we need to define the
\VERB|\NormalTok{<}| operator. It uses the predefined Scala method
\VERB|\NormalTok{sys.}\FunctionTok{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])}
\NormalTok{            sys.}\FunctionTok{error}\NormalTok{(s}\StringTok{"Cannot compare $that 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 \VERB|\NormalTok{Date}| class.

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

\begin{itemize}
\item
  \VERB|\NormalTok{equals}| (i.e.~\VERB|\NormalTok{==}|) and
  \VERB|\NormalTok{<}| because they appear directly in the definition of
  the \VERB|\NormalTok{Date}| class
\item
  \VERB|\NormalTok{!=}|, which is defined in terms of
  \VERB|\NormalTok{equals}|
\item
  the other three because they are inherited from the
  \VERB|\NormalTok{Ord}| trait
\end{itemize}

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

Note: The Scala source code for the \VERB|\NormalTok{OrderedDateTest}|
program is in file
\href{OrderedDateTest.scala}{\VERB|\ExtensionTok{OrderedDateTest.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 \VERB|\NormalTok{Reference}| with a
type \VERB|\NormalTok{T}|, which is the type of its element. The body of
the class declares the \VERB|\NormalTok{contents}| variable, the
argument of the \texttt{set} method, and the return type of the
\VERB|\NormalTok{get}| method to have type \VERB|\NormalTok{T}|.

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

To use this \VERB|\NormalTok{Reference}| class, we need to specify what
type to use for the type parameter \VERB|\NormalTok{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{(s}\StringTok{"Reference contains the half $\{cell.get * 2\}"}\NormalTok{) }
\NormalTok{        \}}
\NormalTok{    \}}
\end{Highlighting}
\end{Shaded}

This example does not need to cast the value returned by the
\VERB|\NormalTok{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.

Note: The Scala source code for the \VERB|\NormalTok{IntegerReference}|
program is in file
\href{IntegerReference.scala}{\VERB|\ExtensionTok{IntegerReference.scala}|}.

\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.

The following online overviews, cheat sheets, and tutorials might also
be useful:

\begin{itemize}
\item
  \href{https://docs.scala-lang.org/tour/tour-of-scala.html}{Tour of
  Scala}
\item
  \href{https://www.jeffshaw.me/cheat/}{Java and Scala Comparison
  Cheatsheet}
\item
  \href{http://www.cis.upenn.edu/~matuszek/Concise\%20Guides/Concise\%20Java\%20to\%20Scala.html}{Concise
  Java to Scala}
\item
  \href{https://learnxinyminutes.com/docs/scala/}{Learn X in Y Minutes,
  Where X = Scala}
\end{itemize}

\hypertarget{source-code-recap}{%
\subsection{Source Code Recap}\label{source-code-recap}}

The Scala source code for the programs in these notes are as follows:

\begin{itemize}
\item
  \href{HelloWorld.scala}{\VERB|\ExtensionTok{HelloWorld.scala}|}
\item
  \href{FrenchDate.scala}{\VERB|\ExtensionTok{FrenchDate.scala}|} and
  \href{MoreDates.scala}{\texttt{MoreDates.scala}}
\item
  \href{Timer.scala}{\VERB|\ExtensionTok{Timer.scala}|} and
  \href{TimerAnonymous.scala}{\VERB|\ExtensionTok{TimerAnonymous.scala}|}
\item
  \href{ComplexNumbers.scala}{\VERB|\ExtensionTok{ComplexNumbers.scala}|},
  \href{ComplexNumbers2.scala}{\VERB|\ExtensionTok{ComplexNumbers2.scala}|},
  and
  \href{ComplexNumbers3.scala}{\VERB|\ExtensionTok{ComplexNumbers3.scala}|}
\item
  \href{ExprCase.scala}{\VERB|\ExtensionTok{ExprCase.scala}|} and
  \href{ExprObj.scala}{\VERB|\ExtensionTok{ExprObj.scala}|}
\item
  \href{OrderedDateTest.scala}{\VERB|\ExtensionTok{OrderedDateTest.scala}|}
\item
  \href{IntegerReference.scala}{\VERB|\ExtensionTok{IntegerReference.scala}|}
\end{itemize}

\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 \VERB|\NormalTok{Tree}| algebraic data type as follows:

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

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

    For example:

    \begin{itemize}
    \tightlist
    \item
      \VERB|\FunctionTok{simplify}\NormalTok{(}\FunctionTok{Add}\NormalTok{(}\FunctionTok{Const}\NormalTok{(}\DecValTok{2}\NormalTok{),}\FunctionTok{Const}\NormalTok{(}\DecValTok{3}\NormalTok{)))}|
      yields
      \VERB|\FunctionTok{Const}\NormalTok{(}\DecValTok{5}\NormalTok{)}|
    \item
      \VERB|\FunctionTok{simplify}\NormalTok{(}\FunctionTok{Add}\NormalTok{(}\FunctionTok{Add}\NormalTok{(}\FunctionTok{Const}\NormalTok{(}\DecValTok{1}\NormalTok{),}\FunctionTok{Const}\NormalTok{(}\DecValTok{1}\NormalTok{)),}\FunctionTok{Mul}\NormalTok{(}\FunctionTok{Const}\NormalTok{(}\DecValTok{1}\NormalTok{),}\FunctionTok{Const}\NormalTok{(}\DecValTok{3}\NormalTok{))))}|
      yields
      \VERB|\FunctionTok{Const}\NormalTok{(}\DecValTok{5}\NormalTok{)}|
    \item
      \VERB|\FunctionTok{simplify}\NormalTok{(}\FunctionTok{Neg}\NormalTok{(}\FunctionTok{Const}\NormalTok{(}\DecValTok{5}\NormalTok{)))}|
      yields
      \VERB|\FunctionTok{Const}\NormalTok{(-}\DecValTok{5}\NormalTok{)}|
    \end{itemize}
  \item
    Extend the \VERB|\NormalTok{simplify}| function to exploit
    mathematical properties such as identity elements
    (\VERB|\NormalTok{x + }\DecValTok{0}\NormalTok{ = x = }\DecValTok{0}\NormalTok{ + x}|),
    and zeros
  \item
    Further extend the \VERB|\NormalTok{simplify}| function to exploit
    associativity (\VERB|\NormalTok{(x + y) + z = x + (y + z)}|,
    commutativity
    (\VERB|\NormalTok{x + }\DecValTok{1}\NormalTok{ = }\DecValTok{1}\NormalTok{ + 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 {[}Schinz 2016{]} to better meet the needs of my
Scala-based courses (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) and Spring 2019 (e.g.~correcting a few Pandoc errors,
improving the markup, adding an explanation of equality, and providing
links to all the Scala source code.).

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}}

\begin{description}
\tightlist
\item[{[}Cunningham 2018{]}]
H. Conrad Cunningham. Exploring Languages with Interpreters `and
Functional Programming, 2018. Available at
\url{https://john.cs.olemiss.edu/~hcc/csci450/ELIFP/ExploringLanguages.html}.
\item[{[}Schinz 2016{]}]
Michel Schinz and Phillipp Haller. A Scala Tutorial for Java
Programmers, 2016. Available at
\url{http://docs.scala-lang.org/tutorials/scala-for-java-programmers.html}.
\end{description}

\hypertarget{terms-and-concepts}{%
\subsection{Terms and Concepts}\label{terms-and-concepts}}

TODO: Add

\end{document}
