0% found this document useful (0 votes)
12 views71 pages

(Ebook) Object-Orientation, Abstraction, and Data Structures Using Scala by Mark C. Lewis Lisa L. Lacher ISBN 9781498732161, 149873216X

The document provides information about the ebook 'Object-Orientation, Abstraction, and Data Structures Using Scala' by Mark C. Lewis and Lisa L. Lacher, including download links and ISBN details. It also lists other recommended ebooks available for download on the same website. The content includes a brief overview of the textbook series and its aims in computing education.

Uploaded by

orsernosalrj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views71 pages

(Ebook) Object-Orientation, Abstraction, and Data Structures Using Scala by Mark C. Lewis Lisa L. Lacher ISBN 9781498732161, 149873216X

The document provides information about the ebook 'Object-Orientation, Abstraction, and Data Structures Using Scala' by Mark C. Lewis and Lisa L. Lacher, including download links and ISBN details. It also lists other recommended ebooks available for download on the same website. The content includes a brief overview of the textbook series and its aims in computing education.

Uploaded by

orsernosalrj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

Visit https://ebooknice.

com to download the full version and


explore more ebooks

(Ebook) Object-Orientation, Abstraction, and Data


Structures Using Scala by Mark C. Lewis; Lisa L.
Lacher ISBN 9781498732161, 149873216X

_____ Click the link below to download _____


https://ebooknice.com/product/object-orientation-
abstraction-and-data-structures-using-scala-7144646

Explore and download more ebooks at ebooknice.com


Here are some recommended products that might interest you.
You can download now and explore!

(Ebook) Object-Orientation, Abstraction, and Data Structures Using


Scala, Second Edition by Lacher, Lisa L.; Lewis, Mark C ISBN
9781498732161, 9781498732178, 9784778650667, 149873216X, 1498732178,
4778650662
https://ebooknice.com/product/object-orientation-abstraction-and-data-
structures-using-scala-second-edition-5742584

ebooknice.com

(Ebook) Biota Grow 2C gather 2C cook by Loucas, Jason; Viles, James


ISBN 9781459699816, 9781743365571, 9781925268492, 1459699815,
1743365578, 1925268497

https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374

ebooknice.com

(Ebook) Matematik 5000+ Kurs 2c Lärobok by Lena Alfredsson, Hans


Heikne, Sanna Bodemyr ISBN 9789127456600, 9127456609

https://ebooknice.com/product/matematik-5000-kurs-2c-larobok-23848312

ebooknice.com

(Ebook) SAT II Success MATH 1C and 2C 2002 (Peterson's SAT II Success)


by Peterson's ISBN 9780768906677, 0768906679

https://ebooknice.com/product/sat-ii-success-
math-1c-and-2c-2002-peterson-s-sat-ii-success-1722018

ebooknice.com
(Ebook) Master SAT II Math 1c and 2c 4th ed (Arco Master the SAT
Subject Test: Math Levels 1 & 2) by Arco ISBN 9780768923049,
0768923042

https://ebooknice.com/product/master-sat-ii-math-1c-and-2c-4th-ed-
arco-master-the-sat-subject-test-math-levels-1-2-2326094

ebooknice.com

(Ebook) Cambridge IGCSE and O Level History Workbook 2C - Depth Study:


the United States, 1919-41 2nd Edition by Benjamin Harrison ISBN
9781398375147, 9781398375048, 1398375144, 1398375047

https://ebooknice.com/product/cambridge-igcse-and-o-level-history-
workbook-2c-depth-study-the-united-states-1919-41-2nd-edition-53538044

ebooknice.com

(Ebook) Objects, Abstraction, Data Structures and Design: Using C++ by


Elliot B. Koffman, Paul A. T. Wolfgang ISBN 9780471467557, 0471467553

https://ebooknice.com/product/objects-abstraction-data-structures-and-
design-using-c-2581014

ebooknice.com

(Ebook) Data Structures And Problem Solving Using C++ by Mark Allen
Weiss ISBN 9780321205001, 0321205006

https://ebooknice.com/product/data-structures-and-problem-solving-
using-c-33556434

ebooknice.com

(Ebook) A Beginner’s Guide to Scala, Object Orientation and Functional


Programming by John Hunt ISBN 9783319757711, 3319757717

https://ebooknice.com/product/a-beginners-guide-to-scala-object-
orientation-and-functional-programming-6868514

ebooknice.com
Object Orientation Abstraction and Data Structures
Using Scala 2nd Edition Edition Mark C. Lewis Digital
Instant Download
Author(s): Mark C. Lewis; Lisa L. Lacher
ISBN(s): 9781498732161, 149873216X
Edition: 2nd Edition
File Details: PDF, 5.97 MB
Year: 2016
Language: english
OBJECT-ORIENTATION,
ABSTRACTION, AND
DATA STRUCTURES
USING

SCALA
SECOND EDITION
CHAPMAN & HALL/CRC
TEXTBOOKS IN COMPUTING

Series Editors

John Impagliazzo Andrew McGettrick


Professor Emeritus, Hofstra University Department of Computer
and Information Sciences
University of Strathclyde

Aims and Scope

This series covers traditional areas of computing, as well as related technical areas, such as
software engineering, artificial intelligence, computer engineering, information systems, and
information technology. The series will accommodate textbooks for undergraduate and gradu-
ate students, generally adhering to worldwide curriculum standards from professional societ-
ies. The editors wish to encourage new and imaginative ideas and proposals, and are keen to
help and encourage new authors. The editors welcome proposals that: provide groundbreaking
and imaginative perspectives on aspects of computing; present topics in a new and exciting
context; open up opportunities for emerging areas, such as multi-media, security, and mobile
systems; capture new developments and applications in emerging fields of computing; and
address topics that provide support for computing, such as mathematics, statistics, life and
physical sciences, and business.

Published Titles

Paul Anderson, Web 2.0 and Beyond: Principles and Technologies


Henrik Bærbak Christensen, Flexible, Reliable Software: Using Patterns and
Agile Development
John S. Conery, Explorations in Computing: An Introduction to Computer
Science
John S. Conery, Explorations in Computing: An Introduction to Computer
Science and Python Programming
Iztok Fajfar, Start Programming Using HTML, CSS, and JavaScript
Jessen Havill, Discovering Computer Science: Interdisciplinary Problems,
Principles, and Python Programming
Ted Herman, A Functional Start to Computing with Python
Pascal Hitzler, Markus Krötzsch, and Sebastian Rudolph, Foundations of
Semantic Web Technologies
Mark J. Johnson, A Concise Introduction to Data Structures using Java
Mark J. Johnson, A Concise Introduction to Programming in Python
Lisa C. Kaczmarczyk, Computers and Society: Computing for Good
Mark C. Lewis, Introduction to the Art of Programming Using Scala
Mark C. Lewis and Lisa L. Lacher, Introduction to Programming and Problem-
Solving Using Scala, Second Edition
Published Titles Continued
Mark C. Lewis and Lisa L. Lacher, Object-Orientation, Abstraction, and Data Structures Using
Scala, Second Edition
Efrem G. Mallach, Information Systems: What Every Business Student Needs to Know
Bill Manaris and Andrew R. Brown, Making Music with Computers: Creative Programming
in Python
Uvais Qidwai and C.H. Chen, Digital Image Processing: An Algorithmic Approach with
MATLAB®
David D. Riley and Kenny A. Hunt, Computational Thinking for the Modern Problem Solver
Henry M. Walker, The Tao of Computing, Second Edition
Aharon Yadin, Computer Systems Architecture
Chapman & Hall/CRC
TEXTBOOKS IN COMPUTING

OBJECT-ORIENTATION,
ABSTRACTION, AND
DATA STRUCTURES
USING

SCALA
SECOND EDITION

Mark C. Lewis
Lisa L. Lacher
CRC Press
Taylor & Francis Group
6000 Broken Sound Parkway NW, Suite 300
Boca Raton, FL 33487-2742
© 2017 by Taylor & Francis Group, LLC
CRC Press is an imprint of Taylor & Francis Group, an Informa business

No claim to original U.S. Government works

Printed on acid-free paper


Version Date: 20161109

International Standard Book Number-13: 978-1-4987-3216-1 (Paperback)

This book contains information obtained from authentic and highly regarded sources. Reasonable efforts have been
made to publish reliable data and information, but the author and publisher cannot assume responsibility for the valid-
ity of all materials or the consequences of their use. The authors and publishers have attempted to trace the copyright
holders of all material reproduced in this publication and apologize to copyright holders if permission to publish in this
form has not been obtained. If any copyright material has not been acknowledged please write and let us know so we may
rectify in any future reprint.

Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmitted, or uti-
lized in any form by any electronic, mechanical, or other means, now known or hereafter invented, including photocopy-
ing, microfilming, and recording, or in any information storage or retrieval system, without written permission from the
publishers.

For permission to photocopy or use material electronically from this work, please access www.copyright.com (http://
www.copyright.com/) or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923,
978-750-8400. CCC is a not-for-profit organization that provides licenses and registration for a variety of users. For
organizations that have been granted a photocopy license by the CCC, a separate system of payment has been arranged.

Trademark Notice: Product or corporate names may be trademarks or registered trademarks, and are used only for
identification and explanation without intent to infringe.
Visit the Taylor & Francis Web site at
http://www.taylorandfrancis.com
and the CRC Press Web site at
http://www.crcpress.com
Contents

List of Figures xvii

List of Tables xxiii

Preface xxv

1 Scala Language Basics 1


1.1 First Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 Variables and Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4 Statements and Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.4.1 Lambda Expressions/Closures . . . . . . . . . . . . . . . . . . . . 9
1.5 Control Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.5.1 Conditionals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.5.2 Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.5.3 Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.6 Declarations and Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.7 Essential Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.7.1 Standard Input and import Statements . . . . . . . . . . . . . . . 19
1.7.2 Basic Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.7.2.1 Array and List . . . . . . . . . . . . . . . . . . . . . . . 21
1.7.2.2 Creating Collections Using fill . . . . . . . . . . . . . . 22
1.7.2.3 Creating Collections Using tabulate . . . . . . . . . . . 22
1.7.2.4 Creating Arrays Using new . . . . . . . . . . . . . . . . . 23
1.7.2.5 Creating Lists Using Cons . . . . . . . . . . . . . . . . . 24
1.7.2.6 Range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
1.7.2.7 Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
1.7.2.8 Higher-Order Methods . . . . . . . . . . . . . . . . . . . 29
1.7.3 The Option Type . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
1.7.4 Text Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
1.8 Other Language Features . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
1.8.1 Unfinished Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
1.8.2 Named Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
1.8.3 Default Parameter Values . . . . . . . . . . . . . . . . . . . . . . . 38
1.8.4 Curried Functions/Methods . . . . . . . . . . . . . . . . . . . . . . 38
1.8.5 Pass-by-Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
1.9 The Read, Evaluate, Print Loop (REPL) . . . . . . . . . . . . . . . . . . 41
1.10 Putting It Together . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
1.11 End of Chapter Material . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
1.11.1 Summary of Concepts . . . . . . . . . . . . . . . . . . . . . . . . . 43
1.11.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

vii
viii Contents

2 Basics of Object-Orientation and Software Development 51


2.1 The Meaning of Object-Orientation . . . . . . . . . . . . . . . . . . . . . 51
2.2 What Are classes? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
2.3 Software Development Stages . . . . . . . . . . . . . . . . . . . . . . . . . 59
2.4 Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
2.5 Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
2.6 Bank Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
2.6.1 Bank Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
2.6.2 Bank Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
2.6.3 Bank Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 66
2.6.4 Making an Application . . . . . . . . . . . . . . . . . . . . . . . . 72
2.7 Making Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
2.8 End of Chapter Material . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
2.8.1 Summary of Concepts . . . . . . . . . . . . . . . . . . . . . . . . . 77
2.8.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
2.8.3 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79

3 Details of Object-Orientation in Scala 81


3.1 The 2D Vector classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
3.1.1 this Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
3.2 Special Methods and Symbolic Names . . . . . . . . . . . . . . . . . . . . 84
3.2.1 Scala Naming Rules/Symbolic Names . . . . . . . . . . . . . . . . 84
3.2.1.1 Precedence and Associativity . . . . . . . . . . . . . . . . 88
3.2.2 Unary Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
3.2.3 Property Assignment Methods . . . . . . . . . . . . . . . . . . . . 89
3.2.4 The apply Method . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
3.2.5 The update Method . . . . . . . . . . . . . . . . . . . . . . . . . . 92
3.3 object Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
3.3.1 Companion Objects . . . . . . . . . . . . . . . . . . . . . . . . . . 94
3.4 Final Versions of 2D Vectors . . . . . . . . . . . . . . . . . . . . . . . . . 96
3.5 case classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
3.6 Encapsulation/Separating Interface from Implementation . . . . . . . . . 102
3.7 Revisiting the API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
3.8 import Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
3.9 End of Chapter Material . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
3.9.1 Summary of Concepts . . . . . . . . . . . . . . . . . . . . . . . . . 106
3.9.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
3.9.3 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109

4 Abstraction and Polymorphism 115


4.1 Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
4.2 Inclusion Polymorphism (Inheritance and Subtyping) . . . . . . . . . . . . 118
4.2.1 Inheritance in the Scala Type System . . . . . . . . . . . . . . . . 122
4.2.2 Inheritance in Scala Code . . . . . . . . . . . . . . . . . . . . . . . 122
4.2.3 private Visibility and Inheritance . . . . . . . . . . . . . . . . . . 126
4.2.4 protected Visibility . . . . . . . . . . . . . . . . . . . . . . . . . . 127
4.2.5 Calling Methods on the Supertype . . . . . . . . . . . . . . . . . . 127
4.2.6 Abstract Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
4.2.7 traits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
4.2.8 final . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
4.2.9 Method Resolution . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Contents ix

4.2.10 Inheriting from Function Types . . . . . . . . . . . . . . . . . . . . 134


4.2.11 Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
4.3 Parametric Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
4.3.1 Parametric Types . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
4.3.2 Parametric Functions and Methods . . . . . . . . . . . . . . . . . 140
4.3.2.1 Parametric Sorts . . . . . . . . . . . . . . . . . . . . . . . 142
4.3.3 Type Bounds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
4.3.3.1 Type Bounds and Sorting . . . . . . . . . . . . . . . . . . 145
4.4 End of Chapter Material . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
4.4.1 Summary of Concepts . . . . . . . . . . . . . . . . . . . . . . . . . 147
4.4.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
4.4.3 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148

5 GUIs and Graphics 149


5.1 Project Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
5.2 ScalaFX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
5.3 Drawing Program Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
5.3.1 Menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
5.3.2 Panes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
5.3.3 Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
5.4 Drawing Program Design . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
5.5 Interactivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
5.5.1 Properties, Observables, and Bindings . . . . . . . . . . . . . . . . 166
5.6 Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
5.6.1 Shapes and Scene Graph . . . . . . . . . . . . . . . . . . . . . . . 167
5.6.2 Canvas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
5.7 Keyboard and Mouse Input . . . . . . . . . . . . . . . . . . . . . . . . . . 174
5.8 Animation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
5.9 Other Elements of ScalaFX . . . . . . . . . . . . . . . . . . . . . . . . . . 179
5.10 End of Chapter Material . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
5.10.1 Summary of Concepts . . . . . . . . . . . . . . . . . . . . . . . . . 179
5.10.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
5.10.3 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182

6 Other Collection Types 185


6.1 The scala.collection Packages . . . . . . . . . . . . . . . . . . . . . . . . . 185
6.1.1 scala.collection.immutable . . . . . . . . . . . . . . . . . . . . . . . 186
6.1.2 scala.collection.mutable . . . . . . . . . . . . . . . . . . . . . . . . 188
6.2 Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
6.2.1 Running through Sets . . . . . . . . . . . . . . . . . . . . . . . . . 190
6.2.2 Mutable vs. Immutable . . . . . . . . . . . . . . . . . . . . . . . . 191
6.2.3 Using a Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
6.3 Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
6.3.1 Looping through a Map . . . . . . . . . . . . . . . . . . . . . . . . 195
6.3.2 Using Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
6.4 Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
6.5 Collections as Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
6.6 Project Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
6.6.1 Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
6.6.2 Adding Drawables . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
6.7 End of Chapter Material . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
x Contents

6.7.1 Summary of Concepts . . . . . . . . . . . . . . . . . . . . . . . . . 208


6.7.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
6.7.3 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209

7 Stacks and Queues 213


7.1 Abstract Data Types (ADTs) . . . . . . . . . . . . . . . . . . . . . . . . . 214
7.2 Operations on Stacks and Queues . . . . . . . . . . . . . . . . . . . . . . . 214
7.3 Real Meaning of O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
7.4 O(1) Requirement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
7.5 Array-Based Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
7.6 Array-Based Queue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
7.7 Unit Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
7.7.1 Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
7.7.2 Writing Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
7.7.3 Test Suites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
7.7.4 Test-Driven Development . . . . . . . . . . . . . . . . . . . . . . . 229
7.8 RPN Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
7.9 Breadth-First Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
7.10 End of Chapter Material . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
7.10.1 Summary of Concepts . . . . . . . . . . . . . . . . . . . . . . . . . 238
7.10.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
7.10.3 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239

8 Multithreading and Concurrency 243


8.1 The Multicore and Manycore Future . . . . . . . . . . . . . . . . . . . . . 244
8.2 Threads (Conceptual) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
8.3 Futures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
8.3.1 Using foreach, map, and flatMap . . . . . . . . . . . . . . . . . . 247
8.3.2 Working in Parallel . . . . . . . . . . . . . . . . . . . . . . . . . . 251
8.3.3 Futures with for Loops . . . . . . . . . . . . . . . . . . . . . . . . 253
8.3.4 Getting a Result . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
8.4 Parallel Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
8.4.1 Parallel for Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
8.4.2 Parallel reduce, fold, and aggregate . . . . . . . . . . . . . . . . 259
8.4.3 When to Use Parallel Collections . . . . . . . . . . . . . . . . . . . 260
8.5 Race Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
8.6 Synchronization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
8.7 Deadlock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
8.8 Multithreading in GUIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
8.9 Multithreaded Mandelbrot (Project Integration) . . . . . . . . . . . . . . 269
8.10 Actors and Akka . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
8.10.1 Akka . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
8.10.2 Actors Communicating . . . . . . . . . . . . . . . . . . . . . . . . 278
8.10.3 The Ask Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
8.10.4 Be Careful with sender and this . . . . . . . . . . . . . . . . . . 283
8.10.5 The Actor Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . 284
8.10.6 Error Handling and the Actor Lifecycle . . . . . . . . . . . . . . . 287
8.10.7 Routers (Project Integration) . . . . . . . . . . . . . . . . . . . . . 291
8.10.8 More to Akka . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
8.11 End of Chapter Material . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
8.11.1 Summary of Concepts . . . . . . . . . . . . . . . . . . . . . . . . . 297
Contents xi

8.11.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299


8.11.3 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300

9 Low-Level Multithreading and Java Libraries 303


9.1 Basic Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
9.1.1 Wait/Notify . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
9.1.2 Other Thread Methods . . . . . . . . . . . . . . . . . . . . . . . . 309
9.2 Concurrency Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
9.2.1 Executors and Executor Services . . . . . . . . . . . . . . . . . . . 311
9.2.2 Callable and Java Futures . . . . . . . . . . . . . . . . . . . . . . . 311
9.2.3 Parallel Data Structures . . . . . . . . . . . . . . . . . . . . . . . . 314
9.2.3.1 Shared Barriers . . . . . . . . . . . . . . . . . . . . . . . 314
9.2.3.2 The Exchange . . . . . . . . . . . . . . . . . . . . . . . . 315
9.2.3.3 Assembly Line . . . . . . . . . . . . . . . . . . . . . . . . 316
9.2.3.4 Ticketed Passengers . . . . . . . . . . . . . . . . . . . . . 317
9.2.3.5 Other Threadsafe Types . . . . . . . . . . . . . . . . . . 317
9.2.4 Atomic (java.util.concurrent.atomic) . . . . . . . . . . . . . . 317
9.2.5 Locks (java.util.concurrent.locks) . . . . . . . . . . . . . . . 318
9.3 End of Chapter Material . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
9.3.1 Summary of Concepts . . . . . . . . . . . . . . . . . . . . . . . . . 319
9.3.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
9.3.3 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321

10 Stream I/O and XML 323


10.1 The java.io Package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
10.2 Streams for Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
10.3 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
10.3.1 try-catch-finally Revisited . . . . . . . . . . . . . . . . . . . . . 327
10.3.2 Effect of Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . 329
10.3.3 Loan Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
10.4 Decorating Streams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
10.4.1 Buffering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
10.4.2 Binary Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
10.5 Serialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
10.5.1 Binary Serialization . . . . . . . . . . . . . . . . . . . . . . . . . . 335
10.5.2 XML Serialization . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
10.5.2.1 Nature of XML . . . . . . . . . . . . . . . . . . . . . . . 340
10.5.2.2 XML in Scala Code . . . . . . . . . . . . . . . . . . . . . 342
10.5.2.3 Serializing to XML . . . . . . . . . . . . . . . . . . . . . 344
10.6 Saving Drawings (Project Integration) . . . . . . . . . . . . . . . . . . . . 345
10.7 End of Chapter Material . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
10.7.1 Summary of Concepts . . . . . . . . . . . . . . . . . . . . . . . . . 366
10.7.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
10.7.3 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367

11 Networking 369
11.1 TCP and UDP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
11.2 Sockets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
11.2.1 TCP Sockets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
11.2.2 UDP Sockets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
11.2.3 Streams from Sockets . . . . . . . . . . . . . . . . . . . . . . . . . 373
xii Contents

11.3 URLs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378


11.4 Remote Method Invocation (RMI) . . . . . . . . . . . . . . . . . . . . . . 380
11.5 Collaborative Drawing (Project Integration) . . . . . . . . . . . . . . . . . 388
11.6 End of Chapter Material . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
11.6.1 Summary of Concepts . . . . . . . . . . . . . . . . . . . . . . . . . 401
11.6.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
11.6.3 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402

12 Linked Lists 405


12.1 The List/Seq ADT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
12.2 Nature of Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406
12.3 Nature of Linked Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406
12.4 Mutable Singly Linked List . . . . . . . . . . . . . . . . . . . . . . . . . . 408
12.4.1 Implementing mutable.Buffer . . . . . . . . . . . . . . . . . . . . 412
12.4.2 Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
12.5 Mutable Doubly Linked List . . . . . . . . . . . . . . . . . . . . . . . . . . 417
12.6 Immutable Singly Linked List . . . . . . . . . . . . . . . . . . . . . . . . . 422
12.7 Linked List-Based Stacks and Queues . . . . . . . . . . . . . . . . . . . . 425
12.7.1 Linked List-Based Stack . . . . . . . . . . . . . . . . . . . . . . . . 425
12.7.2 Linked List-Based Queue . . . . . . . . . . . . . . . . . . . . . . . 426
12.8 Project Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
12.9 End of Chapter Material . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
12.9.1 Summary of Concepts . . . . . . . . . . . . . . . . . . . . . . . . . 427
12.9.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
12.9.3 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429

13 Priority Queues 431


13.1 Two Approaches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
13.1.1 Searching by Priority . . . . . . . . . . . . . . . . . . . . . . . . . 432
13.1.2 Sorted Linked List . . . . . . . . . . . . . . . . . . . . . . . . . . . 432
13.1.3 Problems with Arrays . . . . . . . . . . . . . . . . . . . . . . . . . 434
13.2 Project Integration: Discrete Event Simulation . . . . . . . . . . . . . . . 435
13.2.1 Cell Splitting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
13.2.2 Collision Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
13.3 End of Chapter Material . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
13.3.1 Summary of Concepts . . . . . . . . . . . . . . . . . . . . . . . . . 445
13.3.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
13.3.3 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446

14 Refactoring 449
14.1 Smells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
14.2 Refactorings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
14.2.1 Built-in Refactoring Methods . . . . . . . . . . . . . . . . . . . . . 453
14.2.2 Introduce Null Object . . . . . . . . . . . . . . . . . . . . . . . . . 454
14.2.3 Add and Remove Parameter . . . . . . . . . . . . . . . . . . . . . 454
14.2.4 Cures for Switch Statements . . . . . . . . . . . . . . . . . . . . . 455
14.2.5 Consolidate Conditional Expression . . . . . . . . . . . . . . . . . 456
14.2.6 Convert Procedural Design to Objects . . . . . . . . . . . . . . . . 457
14.2.7 Encapsulate Collection . . . . . . . . . . . . . . . . . . . . . . . . 457
14.2.8 Push Down or Pull Up Field or Method . . . . . . . . . . . . . . . 458
14.2.9 Substitute Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . 458
Contents xiii

14.3 End of Chapter Material . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459


14.3.1 Summary of Concepts . . . . . . . . . . . . . . . . . . . . . . . . . 459
14.3.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
14.3.3 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459

15 Recursion 461
15.1 Refresher . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
15.2 Project Integration: A Maze . . . . . . . . . . . . . . . . . . . . . . . . . . 462
15.2.1 The Recursive Approach . . . . . . . . . . . . . . . . . . . . . . . 462
15.2.2 Graphical Editing . . . . . . . . . . . . . . . . . . . . . . . . . . . 464
15.2.3 Longest Path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
15.2.4 Optimizing the Maze . . . . . . . . . . . . . . . . . . . . . . . . . 471
15.3 Graph Traversals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473
15.4 Divide and Conquer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
15.4.1 Merge Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
15.4.2 Quicksort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484
15.4.3 Formula Parser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
15.5 End of Chapter Material . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
15.5.1 Summary of Concepts . . . . . . . . . . . . . . . . . . . . . . . . . 488
15.5.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
15.5.3 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490

16 Trees 493
16.1 General Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
16.1.1 Implementations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
16.1.2 Traversals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
16.2 Project Integration: Formula Parsing . . . . . . . . . . . . . . . . . . . . . 498
16.2.1 Formula Tree Traversals and In-Order Traversal . . . . . . . . . . 502
16.3 Binary Search Trees: Binary Trees as Maps . . . . . . . . . . . . . . . . . 503
16.3.1 Order Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
16.3.2 Immutable BSTs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
16.4 End of Chapter Material . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514
16.4.1 Summary of Concepts . . . . . . . . . . . . . . . . . . . . . . . . . 514
16.4.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
16.4.3 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516

17 Regular Expressions and Context-Free Parsers 519


17.1 Chomsky Grammars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
17.1.1 Regular Grammars . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
17.1.2 Context-Free Grammars . . . . . . . . . . . . . . . . . . . . . . . . 521
17.1.3 Context-Sensitive Grammars . . . . . . . . . . . . . . . . . . . . . 522
17.1.4 Recursively Enumerable Grammars . . . . . . . . . . . . . . . . . 522
17.2 Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522
17.2.1 Characters and Character Classes . . . . . . . . . . . . . . . . . . 523
17.2.2 Logical Operators and Capturing Groups . . . . . . . . . . . . . . 524
17.2.3 Greedy Quantifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . 525
17.2.4 Boundary Requirements . . . . . . . . . . . . . . . . . . . . . . . . 526
17.2.5 Using Regular Expressions in Code . . . . . . . . . . . . . . . . . . 526
17.2.6 Drawback of Regular Expressions . . . . . . . . . . . . . . . . . . 528
17.3 Context-Free Parsers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529
17.3.1 Default Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530
xiv Contents

17.3.2 Specified Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530


17.4 Project Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531
17.5 End of Chapter Material . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535
17.5.1 Summary of Concepts . . . . . . . . . . . . . . . . . . . . . . . . . 535
17.5.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536
17.5.3 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536

18 Binary Heaps 539


18.1 Binary Heaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
18.1.1 Binary Heaps as Arrays . . . . . . . . . . . . . . . . . . . . . . . . 539
18.2 Heaps as Priority Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
18.3 Heapsort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 547
18.4 End of Chapter Material . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549
18.4.1 Summary of Concepts . . . . . . . . . . . . . . . . . . . . . . . . . 549
18.4.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549
18.4.3 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 550

19 Direct Access Binary Files 551


19.1 Random Access Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551
19.1.1 Fixed Record Length . . . . . . . . . . . . . . . . . . . . . . . . . 552
19.1.2 Indexed Variable Record Length . . . . . . . . . . . . . . . . . . . 557
19.2 Linked Structures in Files . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
19.3 End of Chapter Material . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567
19.3.1 Summary of Concepts . . . . . . . . . . . . . . . . . . . . . . . . . 567
19.3.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567
19.3.3 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 568

20 Spatial Trees 569


20.1 Spatial Data and Grids . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569
20.2 Quadtrees and Octrees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
20.3 kD-Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578
20.4 Efficient Bouncing Balls . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
20.5 End of Chapter Material . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
20.5.1 Summary of Concepts . . . . . . . . . . . . . . . . . . . . . . . . . 582
20.5.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583
20.5.3 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583

21 Augmenting Trees 587


21.1 Augmentation of Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587
21.2 Balanced BSTs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588
21.2.1 Rotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588
21.2.2 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589
21.3 Order-Statistic Trees: Trees as Sequences . . . . . . . . . . . . . . . . . . 593
21.4 Augmented Spatial Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . 600
21.5 End of Chapter Material . . . . . . . . . . . . . . . . . . . . . . . . . . . . 605
21.5.1 Summary of Concepts . . . . . . . . . . . . . . . . . . . . . . . . . 605
21.5.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 605
21.5.3 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 606
Contents xv

22 Hash Tables 609


22.1 Basics of Hash Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 609
22.1.1 Hashing Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 610
22.1.2 Hashing Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . 611
22.2 Chaining . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 612
22.3 Open Addressing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 616
22.3.1 Probing Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617
22.3.2 Removing with Open Addressing . . . . . . . . . . . . . . . . . . . 618
22.3.3 Open Addressing Implementation . . . . . . . . . . . . . . . . . . 619
22.4 End of Chapter Material . . . . . . . . . . . . . . . . . . . . . . . . . . . . 622
22.4.1 Summary of Concepts . . . . . . . . . . . . . . . . . . . . . . . . . 622
22.4.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 623
22.4.3 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 623

Bibliography 625

Index 627
List of Figures

1 This figure shows the relationships between the chapters in this book to
help you pick which ones you want to cover, and in what order. . . . . . . xxviii

1.1 The Scala API looks like this when viewing scala.collection.immutable.List.
The right column shows the various objects, classes, and traits. Selecting
one shows you the visible members inside of it. This is generated using
ScalaDoc on the library code. . . . . . . . . . . . . . . . . . . . . . . . . . 18

2.1 This is a simple example of a UML use case diagram. Actors are drawn as
stick figures. The system being analyzed is a box. The ways in which the
actors use the system are drawn as circles. . . . . . . . . . . . . . . . . . . 61
2.2 This shows the UML class diagram for the Student class from section 2.2
along with a class for a course that contains multiple students. . . . . . . 62
2.3 This figure shows a use case diagram for a potential bank application that
models the customer-facing aspects of a bank. . . . . . . . . . . . . . . . . 64
2.4 This figure shows a class diagram for a potential bank application that
models the customer-facing aspects of a bank. . . . . . . . . . . . . . . . . 65

3.1 This figure shows three vectors, where v3 = v2 + v1 . . . . . . . . . . . . . . 82


3.2 This is part of the right column that you see when you enter the API.
The little circles with the letters c, o, and t indicate whether it is a class,
object, or trait. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104

4.1 This figure shows a limited set of options for the subtyping relationships of
animals as a UML diagram. . . . . . . . . . . . . . . . . . . . . . . . . . . 118
4.2 This is a simple class diagram showing subtypes of fruit. . . . . . . . . . . 119
4.3 This class diagram for fruit adds some methods that we might want and
how they might be overridden in the subclasses. . . . . . . . . . . . . . . . 120
4.4 Diagram of general subtype relationships in Scala. This figure has been
adapted from a similar figure in Programming in Scala by Odersky, Spoon,
and Venners [10]. The thick lines with full arrowheads indicate a subtyping
relationship. The thin lines with an open arrowhead indicate an implicit
conversion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
4.5 This UML class diagram shows what is commonly called the diamond prob-
lem. The challenge with this construct is that it can lead to significant
ambiguity. Different languages have different ways of dealing with this. . . 134

5.1 This is a use case diagram for our drawing program. . . . . . . . . . . . . 150
5.2 This is a simple diagram of what we want our GUI to look like when we are
done with the project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
5.3 This class diagram shows the most of the classes/traits that are relevant
to the ScalaFX scene graph. . . . . . . . . . . . . . . . . . . . . . . . . . . 154
5.4 This is the window that pops up when you run the full version of FirstGUI. 155

xvii
xviii List of Figures

5.5 This is the window that pops up when you run DrawingMain. . . . . . . . 160
5.6 This is a first cut class diagram for our drawing project. . . . . . . . . . . 161
5.7 This is the window that pops up when you run the more complete version
of DrawingMain. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174

6.1 This is a UML diagram of the main types in the scala.collection package.
The collection types we have dealt with, including List[A] and Array[A],
have been under the Seq[A] part of the hierarchy. . . . . . . . . . . . . . . 186
6.2 This is a UML diagram of the main types in the scala.collection.immutable
package. This image is significantly simplified. If you look in the API you
will see that most of the types inherit from multiple other types. . . . . . 187
6.3 This is a UML diagram of the main types in the scala.collection.mutable
package. This image is significantly simplified. If you look in the API you
will see that most of the types inherit from multiple other types. . . . . . 188

7.1 This figure shows a graphical representation of the meaning of O. The solid
line represents g(n), which would be a measure of the amount of compu-
tation done for an input size n. The dotted line is the function, c × f (n),
where we want to say that g(n) is O(f (n)). This plot labels a position m,
above which the dotted curve is always above the solid curve. . . . . . . . 216
7.2 This figure shows a graphical representation of an Array-based stack and
how it changes over several operations. The stack stores data in the Array
and uses an integer index to keep track of the position of the top. . . . . . 219
7.3 This figure shows a graphical representation of an Array-based queue and
how it changes over several operations. The queue stores data in the Array
and uses integer indexes to keep track of the front and back. . . . . . . . . 223
7.4 This figure shows a graphical representation of an Array-based queue when
it needs to grow on an enqueue. The queue is seen as empty if front==back.
For that reason, the grow operation should happen when the last slot will
be filled. In addition to allocating a bigger Array, the copy operation needs
to move elements of the Array around and alter the location of front and
back. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
7.5 This is what Eclipse shows when a JUnit test is run and all tests are passed.
A green bar means that everything is good. If you get a red bar, then one
or more tests have failed and they will be listed for you. . . . . . . . . . . 228
7.6 This is the drawing program after adding a maze and executing a breadth-
first solution. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
7.7 This figures shows in a graphical way what happens when a breadth-first
search is run. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238

8.1 This figure shows frequencies, transistor counts, and core counts for x86
processors produced between 1978 and 2016. The log scale on the plot makes
it so that exponential curves appear as straight lines. The dotted lines show
fits to the full transistor count data and the frequency data through 2000.
Clock speeds shown are the highest release for each chip. . . . . . . . . . . 245
8.2 This UML diagram shows the main types in the three different parallel
collection packages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
8.3 This is a screen capture of the drawing program with a Mandelbrot image. 270
8.4 This figure shows a single method call between two objects in a basic se-
quence diagram. The key thing to note is that the thread goes with the call.
So when you call methods, the thread weaves around and between objects. 274
List of Figures xix

8.5 This figure shows three objects and two method calls in a basic sequence
diagram that illustrates how a race condition occurs. Even if the objects
properly encapsulate and protect their values, you still have to use synchro-
nization to prevent race conditions. . . . . . . . . . . . . . . . . . . . . . . 275
8.6 This figure shows three actors and two messages in a basic sequence diagram
that illustrates how the actor model prevents race conditions. Each actor
has only a single thread, and messages are processed sequentially, so as
long as mutable state is confined to a single actor, you cannot have race
conditions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
8.7 This figure shows the organization of the actor hierarchy that we are build-
ing in the example in this section. . . . . . . . . . . . . . . . . . . . . . . . 284
8.8 This is a screen capture of the drawing program with a Julia set image. . 292

11.1 This figure shows the different use cases for the socket/stream-based chat
program that we want to write. . . . . . . . . . . . . . . . . . . . . . . . . 374
11.2 This is a screen shot of the RMI chat client with two users connected. . . 387
11.3 This is a screen shot of the collaboration window. On the left is a column
showing shared drawings. On the bottom is a chat area. The main portion
is a shared sketch region where different collaborators can draw using some
simple types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397

12.1 This figure shows what happens when you do an insert and a remove from
an array-based implementation of the list ADT. Note how operations near
the beginning have to do many copies, but operations near the end do not. 407
12.2 This figure shows the basic structure of some different forms of linked lists. 408
12.3 This figure shows what happens with insert and remove on a singly linked
list. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
12.4 This figure shows what happens with insert and remove on a doubly linked
list. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421

13.1 This figure shows how we can do remove from an unsorted array-based
priority queue in O(1) operations after we have done an O(n) search to find
the highest-priority element. . . . . . . . . . . . . . . . . . . . . . . . . . . 435
13.2 This screen shot shows the output of the cell simulation Drawable. The
properties that are used are visible on the left side of the window. . . . . . 439

15.1 This is the drawing program with a sample graph created using DrawGraph. 479

16.1 This figure shows a sample tree with some of the nodes labeled. Node P is
the parent of nodes C, D, and E. D and E are siblings of C. Node P has a
depth of 1 and a height of 2, while node C has a depth of 2 and a height of
1. The size of node P is six, while the size of node C is 2. . . . . . . . . . . 494
16.2 This figure shows the same tree that was displayed in figure 16.1, but draws
arrows for the first-child, next-sibling approach to building the tree. . . . . 495
16.3 This figure shows the same tree that was displayed in figures 16.1 and
16.2. Here, all of the nodes are labeled with letters to aid the discussion of
traversal. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496
16.4 This figure shows the recursion that happens when we parse the formula
3*(x-5)+x*x on the left side. On the right is the tree that we would want
to build from this formula. . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
xx List of Figures

16.5 This is an example of a binary search tree using integer value keys. Searching
for an element in the tree follows steps very much like those a binary search
would perform. The bold arrows show the path that would be taken in a
search for the value 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504
16.6 This figure shows the creation of the BST from figure 16.5. Each element
is placed by running down the tree in the same manner as a search until
we hit a location where there is not a child. A new node with the value is
placed in that location. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505

18.1 This figure shows an example of a binary heap. The numbers are priorities
with higher values being higher priority. Note that there is no problem with
duplicate priorities, unlike keys in a BST. There is also no order requirement
between siblings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
18.2 This figure shows the same heap as in figure 18.1 with subscripts that num-
ber the nodes in breadth-first order. Below that is an array with the elements
at those locations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541
18.3 Adding a new element with a priority of 9 to the heap shown in figure 18.1
goes through the following steps. A bubble is added at the next location in
a complete tree. It moves up until it reaches a point where the new value
can be added without breaking the heap order. . . . . . . . . . . . . . . . 542
18.4 Calling dequeue on the heap at the end of figure 18.3 forces the tree to
go through the following steps. The last element is moved to a temporary
variable, and a stone is placed at the top of the heap. This stone sinks down
until it reaches a point where the temporary can stop without breaking heap
order. The stone always sinks in the direction of the higher-priority child.
If the children have equal priority, it does not matter which side the stone
goes to. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
18.5 This shows a pictorial representation of the alternate data structure that
can be used as an efficient priority queue for collision handling. The top
array keeps the heads of lists for different time brackets during the time
step. The left array is the heads of lists for different particles. All lists are
doubly linked so that nodes can be removed without finding the one before
it. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 548

19.1 The binary file holding the linked list has the following format. The be-
ginning of the file is a header with four values written as Longs. They are
the position of the head node, the position of the tail node, the number of
nodes, and the position of the first free node. . . . . . . . . . . . . . . . . 561
19.2 The nodes of a B-tree can each store a certain number of records. The
number of records is selected to match an optimal size for disk reads and
writes. Non-leaf nodes have references to children at the beginning, end,
and between each record. The records in a node are sorted by a key. In
addition, the nodes in children have to have key values that fall between
the keys of the records they are between, or just below and above for the
beginning and end children. B-trees are always balanced and require few
disk accesses to find a record, but they do potentially waste some space. . 565
List of Figures xxi

19.3 This figure illustrates how adds are done for B-trees. A) shows the tree from
figure 19.2 with the addition of a record whose key value is 75. The 75 is
simply placed in sorted order in a leaf because there is still space left in
that node. For B), a record with a key value of 82 has been added. It would
go right after the 75 record, but there is no more space in that node. Of the
five records that would be in the node, the 75 is the median so it is moved
into the parent and the other records are split into two different nodes. This
process can propagate to higher levels in the tree if the parent is also full.
A new level is created when the root node fills and has to split. . . . . . . 566

20.1 This figure shows an example set of points with a very non-uniform spatial
distribution. A regular grid is laid over this to make it clear how the point
density in the grid cells will vary dramatically. The grid size shown here
works well for many of the low-density regions where there are only a handful
of points per cell. A grid that only had a few points per cell in the high-
density regions would be a very fine grid with an extremely large fraction
of the cells being empty in the low-density areas. . . . . . . . . . . . . . . 574
20.2 This is a quadtree with a number of non-uniformly distributed points to
illustrate how the space is partitioned. For this example, each node is only
allowed to hold a single point. The key advantage of the tree-based approach
is that the resolution does not have to be uniform. Higher-density regions
can divide the space much more finely. . . . . . . . . . . . . . . . . . . . . 575
20.3 This is a kD-tree with a number of non-uniformly distributed points to
illustrate how the space is partitioned. For this example, each node can
hold up to three points. While this example only uses two dimensions, it is
simple to scale the kD-tree higher without adding overhead. . . . . . . . . 579

21.1 This figure shows single rotations to the left and the right. These rotations
can be used when a node becomes unbalanced because the outer grandchild
on the left or the right is too tall relative to the other subtree. . . . . . . . 589
21.2 This figure shows double rotations to the left-right and the right-left. These
rotations can be used when a node becomes unbalanced because the inner
grandchild is too tall. Note that each of these is simply two applications of
the rotations from figure 21.1 . . . . . . . . . . . . . . . . . . . . . . . . . 590
21.3 This figure shows two arrays and their possible tree representations. The
second was arrived at by adding the letter ‘t’ at index 5 of the first. In the
tree, each node has the value, a letter, drawn large with a preceding number
that is the size of the node and a following number that is the index. . . . 594

22.1 This figure shows a graphic representation of the idea behind a hash table.
Keys can be any type of data and are not necessarily ordered. The keys are
mapped, using some function that we call the hash function, to positions
in the storage array. There are many more possible keys than there are
locations in the array, so it is possible to have “collisions” where different
keys map to the same location. . . . . . . . . . . . . . . . . . . . . . . . . 610
xxii List of Figures

22.2 This figure illustrates the challenge that we run into when we have the
option to remove a key-value pair when using open addressing. The left
column shows our words and the value given by our hash function using the
division method for an array with 15 elements. The middle column shows
where all those keys would wind up in the table assuming linear probing.
The third column shows it with “a” removed, which would cause problems
if we go looking for “system.” . . . . . . . . . . . . . . . . . . . . . . . . . 618
List of Tables

0.1 This table shows which projects appear as options in each of the different
chapters. The ‘X’ represents a unique project description. An ‘S’ indicates
that there is a standard description for students to use their own implemen-
tation of a data structure in their project. . . . . . . . . . . . . . . . . . . . xxx

3.1 This table shows the precedence rules for operators in Scala. The precedence
is based on the first character in the operator. . . . . . . . . . . . . . . . . . 88

19.1 This table shows how many bytes are written to disk for each of the basic
value types using either DataOutputStream or RandomAccessFile. . . . . . 552

xxiii
Preface

Thank you for purchasing Object-Orientation, Abstraction, and Data Structures Using
Scala. This book is intended to be used as a textbook for a second or third semester
course in Computer Science. The contents of this book are an expanded second edition
of the second half of Introduction to the Art of Programming Using Scala. The first half
of that book became Introduction to Programming and Problem Solving Using Scala. This
book assumes that the reader has previous programming experience, but not necessarily in
Scala. The introductory chapter is intended to quickly bring the reader up to speed on the
Scala syntax. If you already know Scala, you can skim this chapter for a refresher or skip
it completely.

To the Student
The field of Computer Science has remarkable depth. It has to in order to match the
capabilities and flexibility of the machines that we call “computers”. Your first steps into the
field should have shown you how to structure logic and break down problems, then write up
your instructions for how to solve the problems in the formal syntax of some programming
language. In this book, we want to build upon those capabilities. We want to give you
the tools of object orientation to help you structure solutions to larger, more complex
problems without experiencing mental overload in doing so. We also want to expand on
your knowledge of abstraction so that you can make your code more powerful and flexible.
Of course, all of this is implemented using the Scala programming language, which provides
powerful constructs for expressing both object orientation and abstraction.
One of the key ways that we illustrate these concepts is through the creation of data
structures. Data structures form one of the cornerstones of the field of computer science, and
understanding them is essential for anyone who wants to be an effective software developer.1
We strive to show you not only how these data structures can be written, but the strengths
and weaknesses of each one, so that you can understand when you should consider choosing
different ones.
This book also spends a fair bit of time looking at libraries that provide the functionality
you need to do real programming. This includes things like GUIs, multithreading, and
networking. The goal is to put you in a position where you can solve problems that you are
interested in. These are also vitally important topics that grow in importance every day, so
gaining a basic understanding of them early is something that we think is important.
There are a number of resources available to you that help support the mate-
rial in this book. Much of this material is kept at the book’s website, http://www.
programmingusingscala.net/. We teach our own classes using a flipped format, and there
1 One of the authors recently optimized a section of a professional program that was taking 90 seconds

to run down to 0.3 seconds simply by using more appropriate data structures for key operations.

xxv
xxvi Preface

are video playlists for every chapter in this book available at https://www.youtube.com/
channel/UCEvjiWkK2BoIH819T-buioQ. Even if you are not using this book as part of a
course that uses a flipped format, the videos can do something significant that the book
cannot. They can show you the dynamic aspect of programming. Much of the video content
is live coding where we talk through our thought processes as we construct code. This is a
valuable aspect of programming that prose on paper struggles to communicate. Where the
videos are weak is in total depth of coverage. The book goes into much deeper detail on
many topics than what is covered in the videos.
The playlists on the YouTube channel go beyond the contents of this book. They include
the previous book and a number of more advanced topics. We also post more videos on a
regular basis, so feel free to subscribe to see when additional material becomes available.
Lastly, we have put all of the code in this book in a GitHub repository (https:
//github.com/MarkCLewis/OOAbstractDataStructScala) that you can go through and
pull down. The code is organized into separate packages for each chapter. Occasionally
in the text we present changes to earlier code without showing the entire file that re-
sults. Finished files can always be found in the code repository. We have done the same
for the code written in the videos. It is available at https://github.com/MarkCLewis/
OOAbstractDataStructScalaVideos.
We hope you enjoy this step on your journey to learning computer science and developing
your programming skills.

To the Instructor
Why Scala?
Probably the most distinguishing aspect of this book is the choice of Scala as the imple-
mentation language. As an instructor, you inevitably feel multiple influences when selecting
the language to use for introductory courses, especially given that you do not really want to
focus on language at all. You want to focus on concepts, but you know that those concepts
have to be taught in some language so that students can actually get practice. So you re-
ally want a language that will let you teach the concepts that you feel are most important
without getting in the way. Given this, the next obvious question is, why is Scala a good
language for teaching the concepts covered in this book?
There are several pieces to this answer associated with the different groups of concepts
that are covered in this book. First, Scala is an object-oriented language. Much of the
discussion of the language focuses on the functional features of the language, and while
those are wonderful in many ways and the expressivity they bring is used in this book on
many occasions, the reality is that Scala is more object oriented than it is functional. It is
more object oriented than Java, C++, Python, or most of the other languages one might
consider using to teach this material, with the possible exception of Smalltalk and Ruby. All
values in Scala are objects, which simplifies many details compared to languages where there
are distinctions between primitives and objects.2 There is no concept of “static”, which is
replaced by singleton object declarations which fit much better in the OO model. Even the
functions are really just objects with an implementation of the apply method.
2 A favorite example of this is converting between a commonly used type. In Java, why do you say i =

(int)x, but i = Integer.parseInt(s)? Why can you not make an ArrayList<int> but you can make an
int[] which has very different syntax? In Scala you can say x.toInt and s.toInt and you can use the same
Int type with all of your collections which all have uniform syntax.
Preface xxvii

Scala provides many different tools for creating abstraction in code. You have the stan-
dard OO approaches through polymorphism with inheritance and type parameters. You also
have the approaches found in functional languages created by the ease of passing functions
around. Support for pass-by-name adds yet another tool for creating abstraction in code
that is not available in many languages.
Some instructors will also be happy to know that these abstraction tools are all im-
plemented in a statically typed manner. We consider knowledge of type systems to be an
integral part of programming and CS in general. Static type systems have their own formal
logic that can help to structure student thinking and there are certain topics that simply
cannot be taught in dynamically typed languages.
These factors all contribute to the use of Scala for teaching data structures. The language
works very well for teaching students how to construct type-safe collections of their own
from the ground up.
Beyond the keywords in the title of the book, we like to introduce interesting and useful
libraries, which are abundant in both Scala and the broader JVM environment. The ability
to use the advanced multithreading libraries in Scala while also leaning on Java libraries for
things like networking, is remarkably advantageous.
One of the key features of Scala is that it is not opinionated. It lets you do things your
way. Some people lament that in professional environments. However, in the classroom, that
means that you can teach what and how you want. You can use declarative constructs if
you want to focus on higher level thinking or use imperative constructs when you want your
students to have to deal with the details. A general idea behind Scala is that there is no
silver bullet for most problems in computer science, so a language should provide you with
options to do things in the way that you feel is best. We believe that this matters as much
in the classroom as in other venues.
Lastly, there are the influences beyond pedagogy. There are considerations of how a
language fits into the full departmental curriculum and how it impacts students outside
of your curriculum. Scala works well beyond just the introductory courses. It is broadly
used in web development, has a significant range of tools for parallelism, and thanks to the
Spark library, it has become a dominant force in the area of data analytics. As a result,
it is not hard to envision Scala being used in later courses in the curriculum. As for real-
world usage, we would argue that Scala sits in the sweet spot for pedagogy. It is being
broadly used outside of academia. At the time of this writing, it was number 14 on the
latest RedMonk language ranking, sitting at roughly equal position on both the GitHub
and StackOverflow axes of that ranking. This is high enough that you can point students,
parents, and colleagues to real-world usage. However, it is far enough down that students
are less likely to be able to find answers to all of your programming assignments with a
simple Google search.
While there is no perfect language for anything, we do believe that for these reasons,
and likely others that we have missed, Scala is a good option for introductory programming
courses.

Structure and Contents


This book is pretty much what the title says it is. We strive to give students a firm
foundation in the key principles of object orientation while building their ability to use
abstraction in various forms, including multiple forms of polymorphism. A lot of this is
communicated in the form of data structures, and we believe that this book can serve as a
textbook for a basic course on data structures. We present basic order analysis and discuss
the relative strengths and weaknesses of the various implementations of different Abstract
Data Types along with showing implementations of those ADTs in Scala.
xxviii Preface

FIGURE 1: This figure shows the relationships between the chapters in this book to help
you pick which ones you want to cover, and in what order.
Preface xxix

There are also a few additional topics thrown in that we feel can go well in a CS2
course. These include GUIs, basic graphics, multithreading, and networking. We picked
these because they allow students to write more “real” programs that they will hopefully
find interesting. Also, in the case of multithreading and networking, these topics grow in
importance every day, and having some exposure to them early is something we feel benefits
students.
This book does assume that students have had at least one semester of previous pro-
gramming instruction. If your students are coming to this book without having used Scala
previously, the first chapter is intended to be a quick introduction to the key points of the
language. We provide an appendix with a basic refresher on recursion for those students
who did not cover that previously. We do not include basic sorting and searching. If your
students have not previously seen that, you will want to cover it in some form at or before
chapter 4.
There is a lot of material in this book. It is not expected that any course will cover all of
it in one semester. If your students used Introduction to Programming and Problem Solving
Using Scala in a previous semester, then chapters 1 and 5 can be easily skipped. Even with
that, there is still more than most instructors would wish to cover in a semester. This is
intentional, as we expect that you will focus on different material based on whether you are
using this for a 2nd or 3rd semester course. Figure 1 shows a basic representation of the
chapter dependencies in this book. A line between chapters implies that the later chapter
uses material covered in the earlier one. As you can see, there are a number of chapters off to
the side that can be skipped or covered in a different order without running into problems.
As mentioned in the section addressed to the student reader, there are a number of online
resources associated with this book. The online videos were created by us for use in our own
flipped classroom setting. If you use a blended approach in any way, we strongly encourage
you to make use of these videos. Producing videos takes roughly as long as writing a book,
and they allow students to see live coding, which we consider to be extremely valuable.
There is also a GitHub repository with all of the code that we wrote for this book. We
hope that you find these, and other resources on the course website, to be of value in your
teaching.

Projects
One of the key issues with teaching object orientation is that the strengths of the OO
approach really come out when programs get longer. In order to highlight this with students,
you have to have them see and work on larger pieces of code. Beginning in chapter 5, we
create a project that is utilized in most of the later chapters in the book to illustrate how to
use the concepts that are discussed in an application that is a few thousand lines in length.
We also provide both exercises and projects at the end of each chapter. The exercises
are intended to be simple, one-off tasks that students can use to test their knowledge of
the contents of that chapter. The projects are continued across multiple chapters to give
students a chance to build their own larger applications. Table 0.1 shows which chapters
the projects appear in so that you can determine which ones are best suited to the material
that you intend to cover from this book.
The table uses short names for the projects. Here are brief descriptions as well. Long
descriptions can be found in the projects section of chapter 3.
• MUD - This is a multi-player text-based game. It works particularly well for high-
lighting the actor style of parallelism, but can be done without that.
• Spider - This is a web spider/crawler that follows links on web pages to collect infor-
mation from a site.
xxx Preface
Chapter MUD Spider Game Math Image Sim Stocks Movies L-Systems
1. Scala Basics
2. OO Basics
3. OO Details X X X X X X X X X
4. Polymorphism X X X
5. GUIs X X X X X X X X X
6. Collections X X X X X X X X X
7. Stacks & Queues X X X X X X X X X
8. Multithreading X X X X X X X X
9. Low-Level Threads X X
10. Streams X X X X X X X X X
11. Networking X X X X X X X X
12. Linked Lists S S S S S S S S S
13. Priority Queues X X X X X X X
14. Refactor
15. Recursion X X X X X X X X X
16. Trees X X X X X X X X X
17. Regex/Parsers X X X X X X X X X
18. BinaryHeaps S S S S S S S
19. Binary Files X X X X X X
20. Spatial Trees X X X X X X X
21. Augmented Trees X X X X X X X
22. Hash Tables S S S S S S S S S

TABLE 0.1: This table shows which projects appear as options in each of the different
chapters. The ‘X’ represents a unique project description. An ‘S’ indicates that there is a
standard description for students to use their own implementation of a data structure in
their project.

• Game - This option has students create a graphical game. There are technically two
paths to this, one for a standalone game and one for a networked game.
• Math - This is short for “Mathematics Workbench”. It has students write something
like a baby Mathematica R worksheet program.
• Sim - This is short for “Simulation Workbench” in which students write a variety of
types of simulations and integrate them into a single, larger project. The simulations
include N-body physics simulations as well as discrete event simulations.
• Stocks - This is a networked, stock portfolio management system that involves pulling
stock data from the web and helps users manage their stock portfolio.
• Movies - This project involves keeping an inventory of movies with the eventual goal
of setting up a little business that rents/streams movies to users. Users can track
rental requests, favorites, and movies already rented.
• L-Systems - In this project, students play with the formal grammars known as L-
systems that can have interesting turtle graphic interpretations that produce fractals
and structures that resemble biological forms.
Chapter 1
Scala Language Basics

1.1 First Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2


1.2 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 Variables and Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4 Statements and Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.4.1 Lambda Expressions/Closures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.5 Control Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.5.1 Conditionals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.5.2 Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.5.3 Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.6 Declarations and Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.7 Essential Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.7.1 Standard Input and import Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.7.2 Basic Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.7.2.1 Array and List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.7.2.2 Creating Collections Using fill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
1.7.2.3 Creating Collections Using tabulate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
1.7.2.4 Creating Arrays Using new . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.7.2.5 Creating Lists Using Cons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
1.7.2.6 Range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
1.7.2.7 Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
1.7.2.8 Higher-Order Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
1.7.3 The Option Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
1.7.4 Text Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
1.8 Other Language Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
1.8.1 Unfinished Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
1.8.2 Named Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
1.8.3 Default Parameter Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
1.8.4 Curried Functions/Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
1.8.5 Pass-by-Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
1.9 The Read, Evaluate, Print Loop (REPL) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
1.10 Putting It Together . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
1.11 End of Chapter Material . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
1.11.1 Summary of Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
1.11.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

This book assumes that you have previous programming experience, though perhaps not
with Scala. This chapter is intended to get you up to speed on the basic syntax and semantics
of the Scala language. If you have previous experience with Scala, this can be a refresher.
If your previous experience is in some other language, this chapter will help introduce you
to the key concepts that you need to use in later chapters.
Programming languages are generally classified by different paradigms. A paradigm
is an approach that a language takes to organizing code and solving problems. The four
main paradigms of programming are imperative, functional, object-oriented, and
logic. Scala is generally described as both functional and object-oriented, but it is not
strictly functional, as it allows the imperative style as well. This combining of paradigms
is becoming more common, and even older languages, like Java and Python, have gained
features that also allow them to use aspects of all three of these paradigms. In Scala, one

1
2 Object-Orientation, Abstraction, and Data Structures Using Scala

often prefers more functional approaches, while languages like Java and Python are naturally
imperative with functional features.
Through the course of this book, and hopefully later in your education, the meanings of
these terms and the features of the various paradigms will become clearer. The discussion
in this book will generally explicitly say whether code is written in a way that is more
functional or more imperative, and everything in Scala is fundamentally object-oriented.

1.1 First Application


In this book, we are writing our programs as applications in Scala. If you happened to
use Introduction to Programming and Problem Solving Using Scala [9] previously, most of
that book used the REPL and the scripting environment. Applications were only introduced
at the very end of that book. Here they will be the standard, though simple expressions can
be entered and tested using the REPL as well. The appendices, which are available on the
book website1 introduce some options for how you might want to work with Scala. Pick the
tool that you like best. The rest of this book is generally tool agnostic and code is presented
independent of the way in which you will compile and run it.
Applications in Scala are created by putting a main method in an object declaration.
The following code shows the traditional “Hello World” program.
object HelloWorld {
def main(args:Array[String]):Unit = {
println("Hello world!")
}
}

Depending on your background, different things here might look unfamiliar, so we will
go through the elements one at a time and compare them to what you might have seen
previously. For comparison, and to aid the following discussion, here are similar programs
written in Java and Python.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world!")
}
}

def main():
print("Hello world!")

main()

This Python code is more complex than is really required. The definition of a function is
included to make it more similar to the others for comparison purposes.
The main code of the Scala application is inside of an object declaration. We will discuss
the meaning of the object declaration more in chapter 3 where we will also contrast it to
the more commonly seen class declaration. For now, we will just say that this creates
what is called a singleton object. An object is something that combines both data and
1 http://www.programmingusingscala.net
Scala Language Basics 3

functionality. This declaration begins with the keyword object followed by the name we
want to give our singleton object, then there is a block of code enclosed in curly braces. It
is customary to use the camel case naming scheme in Scala, where each word begins with
a capital letter. The names for objects also start with a capital letter.
All declarations in Scala begin with a keyword. The object keyword declares singleton
objects. The only thing we have put inside the body of our object is a method called main.
Methods are declared with the def keyword. That is followed by the name of the method,
then the parameter list with types in parentheses, the result type after a colon, then an
equal sign and the body of the method. The names of methods should also use camel case
naming, but they should begin with a lowercase letter.
The body of the main method is identified by curly braces. Inside is a single line that
calls the println method and passes it the String that we want to print.
If you are coming to Scala from Java, a lot of this will look familiar. You are used to
seeing class instead of object, and while you would not use def, you would have public
static on your main method. In Java, you put the types before the things they modify, like
the method result and the type of the argument, args. In Scala, types come after things
such as methods, variables, etc., when they are specified, and they are separated by a colon.
If you see a colon in Scala, the thing to the right of it will be a type that is attached to
the thing to the left of it. You also notice that the type is Array[String] in Scala instead
of the String[] that is used in Java. Unlike Java, there is also no semicolon at the end of
the line calling println. Like Java, Scala does use semicolons to separate statements, the
difference is that Scala will infer semicolons at the end of lines where they make sense so
that you do not have to type them. You can still put semicolons at the end of lines, or use
them to separate multiple statements on a single line, but such style is typically frowned
on in Scala.
If you are coming from a Python background, there are good odds that you have just
been writing functions with def and not putting them inside of classes. In Python, there
are no curly braces, and indentation is meaningful to the program. In Scala, it is the curly
braces that are meaningful and indentation, which you really should continue to use, is for
the purposes of human readability.
Unlike Java, Python is a scripting language, and so simple programs like this one are
often just written as executable lines of code with no declarations at all.2 There are good
odds that your introductory course using Python showed you how to declare functions using
def, but it likely did not show you class declarations, or other aspects of object-oriented
programming. Also, while there is some meaning to the concept of “main” in Python, it is
only by convention that programmers write a main function. The language does not require
it. When writing a Scala application, there has to be a main method that takes a single
argument of type Array[String] that is declared inside of an object.3
The biggest difference between Python and Scala is the fact that types are specified
at all. Python is a dynamically typed language. The system it uses for checking types is
commonly called “duck typing”.4 Languages that use duck typing check that values have
the right operations at runtime. If they do not, an error is produced. Scala, on the other
hand, is a statically typed language. This means that, in general, all types are checked
2 Scala scripts are the same way. Writing “Hello World” as a Scala script requires just the single line

println("Hello world!"). The additional lines are provided here because we are focusing on applications,
not scripts.
3 In chapter 4 we will see that you can write applications in a manner where you do not explicitly create

the main method.


4 This term is based on the idea that if it walks like a duck and quacks like a duck, then it must be a

duck. So if a value supports the operations that are needed by a piece of code, then clearly it was of the
right type.
4 Object-Orientation, Abstraction, and Data Structures Using Scala

for correctness by the compiler before the program is run. In this chapter, you will see
that in many places, Scala will figure out types for you. However, there are some places,
like the parameters to functions, where they have to be specified by the programmer. This
might seem tedious, but it allows the compiler to catch a lot of errors earlier, which is very
beneficial for large code bases or projects that are being worked on by many people.5

1.2 Comments
Comments are an essential part of any real-world programming project. Good code is
written in a way so that other people can read it. There are many things that you can do to
help make code readable, including using names that are meaningful. Still, there are times
when you really need to explain what is going on in plain English or to provide additional
information related to the code. This is where comments come in.
Scala style comments are just like Java style comments. You can make a single line
comment with //. Anything that you put after the // on that line will be part of a comment.
Multiline comments begin with a /* and end with a */.6 These comments can include almost
any text you want, including newlines. Just note that a */ ends the comment.
Scala also has an automatic documentation generating tool called ScalaDoc that builds
web-based documentation from code. This tool looks for multiline comments that start with
/**. The extra * does not matter to the compiler, as the /* starts a comment, but it tells
the documentation generator that the comment holds information that is intended to go in
the documentation. For an example of the type of page generated by ScalaDoc, see figure 1.1
later in this chapter, which shows the official Scala library documentation that is generated
with ScalaDoc.
The following code shows what our first application might look like if we added some
comments.
/** Our first application. */
object HelloWorld {
/** The entry method that is run for this application.
*
* @param main the arguments from the command line
*/
def main(args:Array[String]):Unit = {
println("Hello world!") // This call to println sends text to standard output.
}
}

ScalaDoc comments go directly before the declarations that they provide information for.
You can see from the comment on main, that there are some special elements that begin
with @ that provide additional information. In addition to @param, you will see the use of
@return and @constructor later in the book. ScalaDoc is heavily modeled off of JavaDoc,
so if you have experience with using JavaDoc comments, the same attributes will generally
work with ScalaDoc as well.
The comment on println in this example would generally be considered superfluous.
5 One could argue that the lack of compile time type and syntax checking is a big part of the reason why

large projects written for Python 2 have been slow to migrate to Python 3.
6 Note that multiline comments do not have to span multiple lines. They can begin and end on the same

line.
Scala Language Basics 5

It is included primarily to demonstrate single-line comments, but including comments like


this, which only duplicate information that is clearly visible in the code, is a bad idea. Be
careful about comments in your code. They need to be meaningful and provide additional
information to the reader. Over-commenting clutters code and can lead to the code and the
comments getting out of sync. Stale comments that say something that is no longer true
about the code are worse than no comments at all.
Single-line comments in Python start with the hash character (#). A comment may
appear at the start of a line or following a whitespace after a line of code. Multi-line
comments start with triple double quotes (""") or triple single quotes (’’’) before the
comment and then end with matching triple double quotes or triple single quotes at the
end of the comment.

1.3 Variables and Types


In your previous programming experience, you inevitably used variables to give names
to the values that were used in your programs. In Scala, there are two different keywords
that are used for declaring variables: val and var. The following two lines show simple
examples of these two types of declarations.
val name = "Pat Smith"
var age = 18

Here again, there are differences between Scala and other languages you might have learned.
In Python, you do not declare variables, you simply assign values to names and start using
them. This difference exists in part because Python is dynamically typed, so the names do
not have types associated with them. A name can hold a numeric value on one line, then
be assigned a string value on the next, and a list value on a third. Doing so is probably a
bad idea that leads to code that is hard to work with, but Python does nothing to prevent
you from doing it.
If your background is in Java, you are used to declaring variables, but you are used to
putting types in the place where Scala puts val or var. You probably immediately noticed
that this code does not specify types. That is because Scala does local type inference. That
means that Scala will try to figure out the type of things based on information on the
current line. As long as it can, you do not have to specify the type yourself. You can if you
wish though. The previous two lines could have been written, using explicit types, in the
following way.
val name:String = "Pat Smith"
var age:Int = 18

Consistent with what we saw for functions previously, the types are given after the variable
names and separated from the names by a colon. Note that both types start with a capital
letter. In Java, primitive types begin with lowercase letters and object types begin with
capital letters. In Scala, there are no primitive types, and all types begin with capital
letters.7
7 In Scala, the types that were primitives in Java are generally called value types, and the types that

came from Object are called reference types. The distinction between these is discussed more in chapter 4.
6 Object-Orientation, Abstraction, and Data Structures Using Scala

Another difference between Scala and Java is that variable declarations in Scala have to
be given an initial value.8 Inside of methods you cannot have declarations like these where
you would give them values later.
val name:String
var age:Int

This makes the language safer, as uninitialized variables are common sources of errors in
languages that allow uninitialized variables.
An obvious question at this point is, what is the difference between a val declaration
and a var declaration. The answer is that you can change what value is referenced by a
var declaration, but you cannot for a val declaration. In Java terms, the val declaration
is final, and the var declaration is not. So you cannot do later assignments to a val
declaration.
name = "Jane Doe" // This is an error: cannot assign to a val
age = 19 // This compiles just fine

A general rule of thumb in Scala is that you should use val declarations as much as possible,
and only go to var declarations when needed. This is part of the functional paradigm. Odds
are good that your previous exposure to programming has largely used the imperative
paradigm. In this paradigm, re-assignment to variables is common. The values of variables
are called the state of the program, and assignment changes state. The functional paradigm
typically avoids changing or mutating the state. This actually makes it easier to think about
the logic of the program when the value of a variable, once created, does not change.
One last thing to note deals with variable naming conventions. In Scala, variable names
should start with lowercase letters, just like method names. If the name was made up with
multiple words, it would use camel case with the first word in the variable name starting
with a lower case letter and each subsequent word capitalized. The names were also picked
to have meaning. Hopefully this is something that you learned previously: that you should
choose meaningful variable names. Using names that are not meaningful makes programs
much harder to work with, especially for programs that are used over a long period of time
and have multiple programmers editing them.
You can get started in Scala with only a few different types. The following list gives the
basics in alphabetical order.
• Boolean - This type is used for decision logic. It has only two values, true and false,
that can be used as literals in your programs.
• Char - This type is used to represent single character values. You can make literal
characters by putting the character you want in single quotes. For example, ‘a’ or
‘0’.
• Double - This type represents general numbers that might not be integers. They are
stored using the IEEE double precision floating point standard. It is worth noting
that these are not equivalent to the real numbers from mathematics, which have
infinite precision. Numbers that include decimal points, like 3.14, or that use scientific
notation, like 1e100, have this type.
• Int - This type is used to represent integer values. They are stored as 32-bit, signed
binary numbers. If you enter a number that does not have a decimal point or scientific
notation, it will have this type.
8 In chapter 4, we will see that members of classes and traits can be declared without giving them

values, but in Scala that means they are abstract, so the semantics are different from Java.
Scala Language Basics 7

• String - This type is used for representing sequences of characters used for text. You
can create a String literal in your program by putting text between double quotes,
like "Hello".
• Tuples - These are ordered groups of types. You can make them in your code by
putting comma-separated values inside of parentheses. So (1, 3.14, "Hello") is a
tuple with the type (Int, Double, String).

• Unit - This is a type that represents a value that carries no information. There is only
one instance of Unit, and it is written as (). You can get the values out of a tuple
with methods called 1, 2, etc. or using patterns, which will be discussed later.
The fact that every value in Scala is an object means that you can call methods on all
values, regardless of their type. To convert between types, there are methods like toInt or
toString that implement meaningful conversions. So if you had a variable called num with
the value "42", you could use num.toInt to get the value as an integer. For the numeric
types, you can also call MinValue and MaxValue to get the range of allowed values.
This is by no means a complete list of types. Such a list cannot be made, as there are
effectively an infinite number of types. A lot of this book will focus on how we create our
own types in Scala. This is just the minimum set needed to get you up and running in Scala.
We will see more later on.
There are a few other details of the Char and String types that need to be considered
here as well. The normal Char and String literals cannot include line feeds, and there are
challenges dealing with some other characters as well. For that reason, there are escape
characters that likely mirror those that you have seen previously involving a backslash and
various characters. Scala also support raw strings, which are String literals that can
span multiple lines and do not treat the backslash as an escape character. The raw strings
in Scala begin and end with three double quotes. You can put anything inside of them
except for a sequence of three double quotes.
Strings in Scala support concatenation using the plus sign. So you if have the variables
name and age defined above, you can do something like this.
val message = name + " is " + age + "."

This will build a longer String and give it the name message. This syntax is rather long,
and can get unwieldy if you need to append many variables into a formatted String. For
that reason, Scala also supports string interpolation. To make an interpolated String,
simply put the letter s in front of the double quotes. That allows you to insert variables
with a dollar sign. The previous declaration could be written in the following way using an
interpolated String.
val message = s"$name is $age."

If you need a more complex expression in the interpolation, you can put it in curly braces
after the dollar sign. For example, if you wanted to do arithmetic on a value and interpolate
the result you could do something like this.
s"$age times two is ${2*age}."

The curly braces are required after the second dollar sign.9
9 There is another form of interpolation where you prefix the double quote with an f and then use C-style

formatting in the String. We will not use that type of string interpolation in this book.
8 Object-Orientation, Abstraction, and Data Structures Using Scala

1.4 Statements and Expressions


As you are already aware, functions/methods are built out of statements. A statement
in a programming language is much like a sentence in natural language. It is something that
stands on its own. You might have spent less time concerned with the expressions that
typically make up statements. An expression is a piece of code that has a value and a type.
It evaluates to something. This is different from a statement, which just does something.
Variable declarations are statements that associate a name with something, but they do not
provide any value as a result.
The functional aspects of Scala mean that most things that are not declarations are
expressions. This is a significant difference from Java and Python that will be explored
more in section 1.5. You can probably start writing expressions in Scala that work just fine
based on what you know from your previous studies because so many things are common
across programming languages. However, there are differences that are worth noting.
First off, things that look like operators in Scala are really just methods. For example,
when you enter 4+5, Scala actually sees 4.+(5). So + is the name of a method defined in the
type Int. This works with methods that have alphabetic names as well as with those that
have symbolic names, other than the fact that spaces are required when you use alphabetic
names. As an example, the Int type also has a method called min. So it is valid to call
4.min(5), but you can also use the much easier to type 4 min 5 to get the same result.
Precedence rules in Scala are based on the first character in the operator/method, and
it follows the same ordering that is used in other programming languages. Most operators
are left associative. In math, this means that operators of the same precedence are done
from left to right. So 2 − 3 + 4 is (2 − 3) + 4, not 2 − (3 + 4). Operators/methods that end
with a colon in Scala are right associative. Not only are they evaluated from the right to
the left, the method is called on the object that is to the right of the operator. We will see
an example of this in section 1.7.2.
If you come from the Java world, you will find that all of the operators that you are
used to from that language work in the same way in Scala with one significant exception,
the == operator. In Java, == is always an identity check. That is why you normally had to
use the equals method when comparing Strings. In Scala, the == method calls equals,
so it will behave the way you want for everything built into the standard libraries. If you
really want to check for identity, use the eq method/operator. In Python, you use the ==
the same as you would in Scala; however, if you want to check for identity, you would use
the “is” operator.
Scala also defines * on the String type that takes an Int. This allows you to do the
following.
"hi"*5 // this is "hihihihihi"

This is especially handy when you need to repeat a string a variable number of times, often
to produce some type of formatting. This is also something that Python users will find
familiar.
However, there are a few more differences between Scala and Python. First off, in Scala
there is no ** operator provided for doing exponentiation. You can do exponentiation with
the math.pow(x:Double, y:Double):Double method from the library. Similarly, there is
no // operator to do floor division. If you divide two Ints, the result will be a truncated
Int. If you divide two Doubles or a Double and an Int, the result will be a Double that is
as close as possible to the result of that division. The following four expressions illustrate
this.
Scala Language Basics 9

9 / 5 // this is 1 in Scala and Python 2.x, but 1.8 in Python 3.x


9.0 / 5 // this is 1.8 in all
9 / 5.0 // this is 1.8 in all
9.0 / 5.0 // this is 1.8 in all

If you do an operation between two arguments of different types, the less general type is
elevated to the more general type, and the operation is done between those values.
There are also differences between Scala and Python in the area of logical operators.
While Python uses and, or, and not, as the logical operators for Boolean values, Scala
uses the C-style operators of &&, ||, and ! respectively. The && and || are short circuit
operators, so if the value can be determined by the first argument, the second argument is
not evaluated. If you happened to learn Python 2.x, you might also have seen <> used to
represent not equal. Scala, like Python 3.x, will only accept != for not equal.

1.4.1 Lambda Expressions/Closures


A lambda expression is a language construct that allows you to write a function as an
expression. This is a functional programming construct that has found its way into pretty
much every major programming language because it is so useful. Both Java and Python
have lambda expressions, though it is possible that you have not encountered them because
they are often considered to be more advanced constructs in those languages. In Scala,
they are common place, and you really want to know how to create them to create more
expressive code.
The main syntax for a lambda expression in Scala uses the => symbol, which is often
read as “rocket”. To the left of the rocket you put the argument list, parentheses are needed
if there is more than one argument or to specify a type, and to the right you put the
expression for the body of the function. Here is an example where we make a function with
a lambda expression, give it a name, and use it.
val square = (x:Double) => x*x
println(square(3)) // prints out 9.0

We declare square to be the name of the function created by our lambda expression.
Note that you call the lambda expression just like you would a function, by putting the
argument(s) in parentheses after the name. The syntax shown here specifies the type of the
argument for the lambda expression, and Scala figures out the result type. As a general
rule, we do not have to specify things that Scala can figure out, and most of the time, we
will leave that off. Most uses of lambda expressions are in situations where the type of the
lambda expression is completely known.
We can define the same function using a different approach where we put the type on
the name and the lambda expression itself does not have any types.
val square:(Double)=>Double = x => x*x

Here we explicitly give the type of the lambda expression. These types include a rocket,
just as the lambda expressions do. So (Double)=>Double means a function that takes a
Double, represented by the type in parentheses to the left of the rocket, and produces a
Double, shown by the type to the right of the rocket. The parentheses could include multiple
types separated by commas if the function has multiple parameters. They can also be left
off completely if there is only a single parameter. So in this case, the type could have
been written as Double=>Double. Because the type has been specified early, the lambda
expression does not require a type specification on the parameter. This is more similar to
what you will do most of the time when you write lambda expressions.
10 Object-Orientation, Abstraction, and Data Structures Using Scala

There is also a shorter syntax that works for creating lambda expressions that works
for simple expressions where any parameters appear only once each and in order. In these
situations, you can use underscores as place holders for the parameters, and you do not use
the rocket at all. The square function does not fit that rule because the parameter x is used
two times. Instead, we can make a function called twice that simply doubles the value of
the input. Here it is defined using the rocket syntax.
val twice:Double=>Double = x => x*2

Using the underscore syntax, it can be written in the following way.


val twice:Double=>Double = _*2

The rules for exactly when you can use the underscore syntax are somewhat complex. A
practical approach is that if you are using the underscore syntax and you get odd error
messages, you should switch to the rocket syntax.
One last thing to note about lambda expressions is that they should typically be short.
The ones shown here have a single, simple expression as the body of the lambda. This is the
ideal usage. You can use curly braces to make more complex expressions, but if your lambda
expression is more than a few lines long, it probably should not be written as a lambda
expression. You should likely pull it out and make a full method with an informative name
instead. These can be passed into places that call for functions just as easily as lambda
expressions can.

1.5 Control Structures


Every language includes a number of different elements that control the flow of execution
through a program. Most of these constructs are very similar across most languages. For
example, you inevitably worked with an if construct previously. This section will cover the
various control structures that exist in Scala, then compare and contrast them with what
you might have seen previously.

1.5.1 Conditionals
The most basic control structures are conditionals. Every language needs some way of
saying “if”. In most languages, that is exactly how you say it. Scala is not an exception.
The syntax for an if looks like if(conditional ) trueCode else falseCode. The conditional
can be any expression with a Boolean type. The trueCode is what will be evaluated if the
condition is true and the falseCode is what will be evaluated if the condition is false. The
else and the falseCode are both optional, but you will probably include them in Scala
more than you might in other languages. If trueCode or falseCode need to include multiple
statements, curly braces are used to form a block of code.
That description probably sounds very much like what you have seen previously. Where
the if in Scala differs from that seen in most non-functional languages is that it can be
used as either a statement or as an expression. In both Java and Python, the if is only
a statement. It is not an expression because it does not evaluate to a value. In Java and
Python, when you need to make a conditional expression, you do so with the ternary
operator, ?:. Scala has no need for the ternary operator because if works just fine as an
expression.
Scala Language Basics 11

To make this clear, consider the simple example of determining the price of a ticket at
a movie theater. Assume we have a variable called age and that the price of a ticket is $8
for kids under 12 and seniors over 65, and $12 for everyone else. We can write this in an
imperative way using a var declaration and the if as a statement as follows.
var price = 12
if (age < 12 || age > 65) {
price = 8
}

While this is perfectly valid Scala code, this is not how you would normally write this in
Scala. As was mentioned earlier, we would prefer to use a val declaration when possible. In
this situation, that is easy to do if you use the if as an expression instead of a statement.
In that situation, the same code looks like the following.
val price = if (age < 12 || age > 65) 8 else 12

Here the if produces a value, and that value is given the name price. Doing it this way
means that we cannot accidentally mess up the value of price later by doing some other
assignment to it.
It is worth noting that when you use the if as an expression, you almost always want
the blocks of code for the true and false conditions to have the same result type. It really
does not make much sense for the true option to produce an Int and the false option to
produce a String. Such a line of code might be valid Scala code that compiles, but the
value that you get from it will have an unusual type that you cannot do much with.10
Scala allows you to nest any language construct inside of any other language construct.
One implication of this is that you can put an if inside of another if. There is no special
syntax for doing this. Normally, when you nest things, the nested code should be indented
inside of curly braces. One common exception to this rule is when you have if statements
or expressions nested in the else part of another if. In that situation, it is commonly
accepted to format your code in the following way.
if (cond1) {
...
} else if (cond2) {
...
} else if (cond3) {
...
} else {
...
}

For those coming from Python, you should know that there is no pass statement in Scala.
It would be rather unusual to include a condition that you do not want to do anything for
in Scala, but if you do, you can leave the curly braces empty. Note that doing so only really
makes sense when you are using the if as a statement and not an expression. If you use it
as an expression, that means that you are expecting it to result in a value, and the empty
code will produce the type Unit, which generally will not be helpful.
Scala includes a second conditional statement called match. This is a multiway condi-
tional that is decided on a single value. For those with a Java background, it might sound
like a switch statement, but it is a far more powerful construct than the switch. The
general syntax for match is as follows.
10 The details of the type that is produced will be discussed in chapter 4.
12 Object-Orientation, Abstraction, and Data Structures Using Scala

expr match {
case pattern1 => expr1
case pattern2 if cond => expr2
...
}

Each case has a pattern and an optional if guard. An if guard can be used to fil-
ter the results even further. Patterns play a role in a number of different constructs in
Scala. They can be as simple as a value or a name, but they can be more complex. For
example, you can make patterns that match tuples. The following example shows a match
that could be used as part of the classic “Fizzbuzz” problem. In this problem, you are sup-
posed to print all the numbers from 1 to 100 except that you substitute “fizz” for values
that are divisible by 3, “buzz” for values that are divisible by 5, and “fizzbuzz” for values
are that divisible by both. This code assumes that the value in question has the name i.
(i % 3, i % 5) match {
case (0, 0) => "fizzbuzz"
case (0, _) => "fizz"
case (_, 0) => "buzz"
case _ => i.toString
}

The way a match is evaluated is that we go from the first case down, and use the first one
that matches. There are several things to note in this example. The underscore is used as a
wildcard. It matches anything, without giving it a name. You could replace the underscores
with variable names, and the values of that part of the expression would be bound to that
name. You would do that if you wanted to use that value in the expression for that case.
Order clearly matters as the last case matches everything.
Like the if, the match in Scala is an expression. It produces a value given by the
evaluation of the expression for that case. This is being used in the Fizzbuzz example
above. Note that the code does not print or change anything, it simply produces different
values based on the value of i. As with the if, this is generally only meaningful if every
case results in the same type.
The expression in each case can be arbitrary code, and it can span multiple lines. You
do not need curly braces for this, as Scala knows that the current case ends when it sees
the next occurrence of the case keyword. If you are used to the switch statement in Java,
you know that it requires the user to put break statements at the end of cases to prevent
the execution from falling through. That is not the case with match in Scala. Indeed, there
is no break in Scala, and control only goes to one case on an execution of a match. It is
also worth noting that your cases need to cover all possibilities. An error will occur if you
execute a match and none of the cases actually match the expression.

1.5.2 Loops
Another class of language constructs are loops, which give you the ability to have code
execute multiple times. The most general loop is the while loop, which exists in both Java
and Python. The syntax in Scala is identical to that in Java. It looks like the following.

while (condition) body

The body of the loop is generally longer, so most of the time you will see it put in curly
Scala Language Basics 13

braces though they are not technically required if there is only a single statement. The
while loop is a pre-check loop that checks if the condition is true before executing the
body. Scala, like Java, but unlike Python, also includes a post-check do-while loop. The
syntax of this loop is as follows.

do body while(condition)

The only difference between the two is that the body of the do-while loop will always
happen at least once, because the condition is not checked until after it has happened. The
body of the while loop might not happen at all. Both the while and do-while loops should
only be used as statements. If you use them as an expression, the result is always of type
Unit.
The more interesting loop in Scala, and most other languages, is the for loop. In its
simplest usage, the for loop in Scala is like the for-each loop in Java or the for loop in
Python. That is to say that it runs through the elements of a collection. A basic usage of
the for loop in Scala might look like the following.
for (i <- 1 to 10) {
println(i)
}

Looking at this code, it should be pretty clear that it will print the numbers 1 to 10 on
separate lines. A more general view of this basic syntax is as follows.

for (pattern <- collection) body

The pattern can be as simple as a variable name, as seen in the example above, or some-
thing more complex, like tuples. If the pattern does not match an element of the collection,
it is simply skipped over, and no error occurs. We will see more about the collections in
section 1.7.2. The 1 to 10 from the example above produces a type called a Range and it
is actually calling the method to on the Int 1, and passing it an argument of 10. There
is also an until method that makes the upper bound exclusive. The arrow between the
pattern and the collection is often read as “in”. The combination of pattern <- collection
is called a generator.
The for in Scala can do a lot more than just this simple iteration through a single
collection. The example above uses the for loop as a statement that does things, but does
not produce a value. By including the yield keyword before the body, we can turn the for
into an expression.

for (pattern <- collection) yield body

This expression will produce a new collection with the values that the body evaluates to on
each time through the loop. So the following will declare squares to be a collection with the
values 1, 4, 9, ..., 100.
val squares = for (i <- 1 to 10) yield i*i

You can also specify multiple generators in a for loop that are separated by semicolons.
You can also specify if guards and variable declarations. These are also separated by
semicolons. Instead of using semicolons, you can replace the parentheses with curly braces,
and put newlines between each of the different elements in the for. The following example
illustrates multiple generators, a variable definition, and an if guard to create a variable
14 Object-Orientation, Abstraction, and Data Structures Using Scala

called evenProducts that contains the even elements from the products of the numbers
between 1 and 10.
val evenProducts = for (i <- 1 to 10; j <- 1 to 10; product = i*j;
if product % 2 == 0) yield product

This formatting with multiple things on the same line is often challenging to read. You can
put newlines after the semicolons, but Scala also allows for loops that use curly braces in
place of the parentheses. When this syntax is used, semicolons are put on new lines, just
like for normal Scala code. Using this, the previous for loop looks like the following.
val evenProducts = for {
i <- 1 to 10
j <- 1 to 10
product = i*j
if product % 2 == 0
} yield product

This style of formatting with the curly braces using multiple lines is considered proper Scala
style when there are multiple generators, if guards, or variable declarations.
It was mentioned in section 1.5.1 that there is no break in Scala. This also applies to
loops. It simply is not a keyword in the language. Similarly, the continue statement that
you might have used in loops in Java or Python does not exist in Scala.

1.5.3 Error Handling


Exception handling is a common way of dealing with errors in many languages. Java
has a try/catch/finally statement and Python has a try/except/finally statement for
doing this. Scala also includes a try/catch/finally, but the syntax is a bit different from
that of Java. The general syntax is like the following.

try
expression
catch {
case pattern =>expression
case pattern =>expression
...
}
finally expression

The catch or the finally can be left off. The cases in the catch should have an ap-
propriate pattern for the type of error they are set up to handle. The following example
assumes we have a variable called str that holds a String that we would like to convert
to an Int using toInt. If the value of str is not a valid integer value, this will throw a
NumberFormatException. The one case uses a pattern that matches on the type so that
if this happens, a value of 0 is produced. The e that you see in this code is just a variable
name, that will contain a reference to an object of type NumberformatException if str is
not a valid integer value.
val num = try {
str.toInt
} catch {
case e:NumberFormatException => 0
Discovering Diverse Content Through
Random Scribd Documents
that, if the thief does not restore the stolen property, he will be a
dead man within a month.34.1
Similarly in Nias, an island to the west of
Thieves cursed in Sumatra, when a thief cannot be found he is
Nias.
cursed, and to give weight to the curse a dog is
burned alive. While the animal is expiring in torments, the man who
has been robbed expresses his wish that the thief may likewise die
in agony; and they say that thieves who have been often cursed do
die screaming.34.2 Curses are also employed for
Thieves cursed
among the Sea
the same purpose with excellent effect by the Sea
Dyaks of Borneo. Dyaks of Borneo. On this point a missionary bears
the following testimony. “With an experience of
nearly twenty years in Borneo, during which I came into contact with
thousands of the people, I have known of only two instances of theft
among the Dyaks. One was a theft of rice. The woman who lost the
rice most solemnly and publicly cursed the thief, whoever it might be.
The next night the rice was secretly left at her door. The other was a
theft of money. In this case, too, the thief was cursed. The greater
part of the money was afterwards found returned to the box from
which it had been abstracted. Both these incidents show the great
dread the Dyak has of a curse. Even an undeserved curse is
considered a terrible thing, and, according to Dyak law, to curse a
person for no reason at all is a fineable offence.
“A Dyak curse is a terrible thing to listen to. I have only once heard
a Dyak curse, and I am sure I do not want to do so again. I was
travelling in the Saribas district, and at that time many of the Dyaks
there had gone in for coffee-planting; indeed, several of them had
started coffee plantations on a small scale. A woman told me that
some one had over and over again stolen the ripe coffee-berries
from her plantation. Not only were the ripe berries stolen, but the
thief had carelessly picked many of the young berries and thrown
them on the ground, and many of the branches of the plants had
been broken off. In the evening, when I was seated in the public part
of the house with many Dyak men and women round me, we
happened to talk about coffee-planting. The woman was present,
and told us of her experiences, and how her coffee had been stolen
by some thief, who, she thought, must be one of the inmates of the
house. Then she solemnly cursed the thief. She began in a calm
voice, but worked herself up into a frenzy. We all listened horror-
struck, and no one interrupted her. She began by saying what had
happened, and how these thefts had gone on for some time. She
had said nothing before, hoping that the thief would mend his ways;
but the matter had gone on long enough, and she was going to curse
the thief, as nothing, she felt sure, would make him give up his evil
ways. She called on all the spirits of the waters and the hills and the
air to listen to her words and to aid her. She began quietly, but
became more excited as she went on. She said something of this
kind:
“ ‘If the thief be a man, may he be unfortunate in
Curses on a man all he undertakes! May he suffer from a disease
thief.
that does not kill him, but makes him helpless—
always in pain—and a burden to others. May his wife be unfaithful to
him, and his children become as lazy and dishonest as he is himself.
If he go out on the war-path, may he be killed, and his head smoked
over the enemy’s fire. If he be boating, may his boat be swamped
and may he be drowned. If he be out fishing, may an alligator kill him
suddenly, and may his relatives never find his body. If he be cutting
down a tree in the jungle, may the tree fall on him and crush him to
death. May the gods curse his farm so that he may have no crops,
and have nothing to eat, and when he begs for food, may he be
refused, and die of starvation.
“ ‘If the thief be a woman, may she be childless,
Curses on a woman or if she happen to be with child let her be
thief.
disappointed, and let her child be still-born, or,
better still, let her die in childbirth. May her husband be untrue to her,
and despise her and ill-treat her. May her children all desert her if
she live to grow old. May she suffer from such diseases as are
peculiar to women, and may her eyesight grow dim as the years go
on, and may there be no one to help her or lead her about when she
is blind.’
“I have only given the substance of what she said; but I shall never
forget the silence and the awed faces of those who heard her. I left
the house early next morning, so I do not know what was the result
of her curse—whether the thief confessed or not.”36.1
The ancient Greeks seem to have made a very
Thieves cursed in liberal use of curses as a cheap and effective
ancient Greece.
mode of protecting property, which dispenses the
injured party from resorting to the tedious, expensive, and too often
fruitless formalities of the law. These curses they inscribed on tablets
of lead and other materials and deposited either in the place which
was to be protected from depredation or in the temple of the god to
whose tender mercies the criminal was committed. For example, in a
sacred precinct dedicated to Demeter, Persephone, Pluto and other
deities of a stern and inflexible temper at Cnidus, a number of leaden
tablets were found inscribed with curses which consigned the
malefactors of various sorts to the vengeance of the two Infernal
Goddesses, Demeter and her daughter. “May he or she never find
Persephone propitious!” is the constantly repeated burden of these
prayers; and in some of them the sinner is not only excommunicated
in this world but condemned to eternal torments in the world
hereafter. Often the persons who launched these curses were ladies.
One irate dame consigns to perdition the thief who had stolen her
bracelet or the defaulter who had failed to send back her
underclothes.36.2 Another curse, engraved on a marble slab found at
Smyrna, purports that if any man should steal one of the sacred
vessels of a certain goddess or injure her sacred fish, he may die a
painful death, devoured by the fishes.36.3 Sometimes, apparently,
these Greek imprecations were as effective in reclaiming sinners as
Dyak curses are to this day. Thus we read of a curious dedication to
a lunar deity of Asia Minor, by name Men Aziottenos, which declares
how one Artemidorus, having been reviled by a couple of rude
fellows, cursed them in a votive tablet, and how one of the culprits,
having been punished by the god, made a propitiatory offering and
mended his wicked ways.37.1 To prevent people
Landmarks
protected by gods
from encroaching on their neighbours’ land by
and curses. removing the boundary stones, the Greeks
committed landmarks to the special protection of
the great god Zeus;37.2 and Plato dwells with unction on the double
punishment, divine and human, to which the sinner exposed himself
who dared to tamper with these sacred stones.37.3 The Romans
went even further, for they created a god for the sole purpose of
looking after landmarks, and he must have had his hands very full if
he executed all the curses which were levelled not only at every man
who shifted his neighbour’s boundary stone, but even at the oxen
which he employed to plough up his neighbour’s land.37.4 The
Hebrew code of Deuteronomy pronounced a solemn curse on such
as removed their neighbour’s landmarks;37.5 and Babylonian kings
exhausted their imagination in pouring out a flood of imprecations
against the abandoned wretch who thus set at naught the rights of
property in land.37.6 King Nebuchadnezzar in particular, before he
was turned out to grass, appears to have distinguished himself by
the richness and variety of his execrations, if we may judge by a
specimen of them which has survived. A brief extract from this
masterpiece may serve to illustrate the king’s style of minatory
eloquence. Referring to the bold bad man, “be it shepherd or
governor, or agent or regent, levy master or magistrate,” whosoever
he might be, who “for all days to come, for the future of human
habitations,” should dare to tamper with the land which his Majesty
had just marked out, “Ninib, lord of boundaries and boundary-stones,
tear out his boundary stone. Gula, great lady, put lingering illness
into his body, that dark and light red blood he may pour out like
water. Ishtar, lady of countries, whose fury is a flood, reveal
difficulties to him, that he escape not from misfortune. Nusku, mighty
lord, powerful burner, the god, my creator, be his evil demon and
may he burn his root. Whoever removes this stone, in the dust hides
it, burns it with fire, casts it into water, shuts it up in an enclosure,
causes a fool, a deaf man, an idiot to take it, places it in an invisible
place, may the great gods, who upon this stone are mentioned by
their names, curse him with an evil curse, tear out his foundation and
destroy his seed.”38.1
In Africa also superstition is a powerful ally of
Superstition as an the rights of private property. Thus the Balonda
ally of the rights of
private property in place beehives on high trees in the forest and
Africa. protect them against thieves by tying a charm or
“piece of medicine” round the tree-trunks. This
proves a sufficient protection. “The natives,” says Livingstone,
“seldom rob each other, for all believe that certain medicines can
inflict disease and death; and though they consider that these are
only known to a few, they act on the principle that it is best to let
them all alone. The gloom of these forests strengthens the
superstitious feelings of the people. In other quarters, where they are
not subjected to this influence, I have heard the chiefs issue
proclamations to the effect, that real witchcraft medicines had been
placed at certain gardens from which produce had been stolen; the
thieves having risked the power of the ordinary charms previously
placed there.”38.2
The Wanika of East Africa “believe in the power
The Wanika of East and efficacy of charms and amulets, and they
Africa.
wear them in great variety; legs, arms, neck, waist,
hair, and every part of the body are laden with them, either for the
cure or prevention of disease; for the expulsion or repulsion of evil
spirits; and to keep at bay snakes, wild animals, and every other evil.
They hang painted calabashes from the baobab at their hut doors to
keep away thieves; shells, dolls, eggs scratched over with Arabic
characters by the Wana Chuoni (sons of the book) of the coast, are
placed about their plantations and in their fruit-trees, and they
believe that death would overtake a thief who should disregard them.
A charm bound to the leg of a fowl is ample protection for the village.
There is no doubt that, superstitious as the people are, they dread
running great risks for the sake of small gains, and so these charms
answer their purpose.”39.1 Among the Boloki of the
The Boloki of the
Congo.
Upper Congo, when a woman finds that the
cassava roots, which she keeps soaking in a
water-hole, are being stolen, she takes a piece of gum copal, and
fixing it in the cleft of a split stick she puts it on the side of the hole,
while at the same time she calls down a curse on the thief. If the thief
is a man, he will henceforth have no luck in fishing; if she is a
woman, she will have no more success in farming.39.2 The Ekoi of
Southern Nigeria protect their farms against thieves by bundles of
palm leaves to which they give the name of okpata. Should any one
steal from a farm thus protected, he will fall sick and will not recover
unless he gives a certain dance, to which the name of okpata is also
applied.39.3
In the mountains of Marrah, a district of Darfur,
Guardian spirits houses, goods, and cattle are protected against
(damzogs) of
property in Darfur. thieves by certain fierce and dangerous guardian-
spirits called damzogs, which can be bought like
watch dogs. Under the guardianship of such a spiritual protector the
sheep and cows are left free to wander at will; for if any one were
rash enough to attempt to steal or kill one of the beasts, his hand
with the knife in it would remain sticking fast to the animal’s throat till
the owner came and caught the rascal. An Arab merchant, travelling
in Darfur, received from a friend the following account of the way to
procure one of these useful guardians. “At the time when I first
began to trade, my friend, I often heard that damzogs could be
bought and sold, and that to procure one I must apply to the owner
of a damzog, and discuss the price with him. When the bargain is
concluded, it is necessary to give a large gourd of milk to the seller,
who takes it to his house, where are his damzogs. On entering he
salutes them, and goes and hangs up his vase to a hook, saying,
—‘One of my friends—such a one—very rich, is in fear of robbers,
and asks me to supply him with a guardian. Will one of you go and
live in his house? There is plenty of milk there, for it is a house of
blessing, and the proof thereof is, that I bring you this kara of milk.’
The damzogs at first refuse to comply with the invitation. ‘No, no,’
say they, ‘not one of us will go.’ The master of the hut conjures them
to comply with his desires, saying, ‘Oh! let the one that is willing
descend into the kara.’ He then retires a little, and presently one of
the damzogs is heard to flop into the milk, upon which he hastens
and claps upon the vase a cover made of date-leaves. Thus stopped
up he unhooks the kara, and hands it over to the buyer, who takes it
away and hangs it on the wall of his hut, and confides it to the care
of a slave or of a wife, who every morning comes and takes it,
emptying out the milk, washing it and replenishing it, and hanging it
up again. From that time forward the house is safe from theft or
loss.” The merchant’s informant, the Shereef Ahmed Bedawee, had
himself purchased one of these guardian spirits, who proved most
vigilant and efficient in the discharge of his duties; indeed his zeal
was excessive, for he not only killed several slaves who tried to rob
his master, but did summary execution on the Shereef’s own son,
when the undutiful young man essayed to pilfer from his father’s
shop. This was too much for the Shereef; he invited a party of friends
to assist him in expelling the inflexible guardian. They came armed
with guns and a supply of ammunition, and by raking the shop with
repeated volleys of musketry they at last succeeded in putting the
spirit to flight.40.1
Amongst the Nandi of British East Africa nobody
The curses of dares to steal anything from a smith; for if he did,
smiths and potters.
the smith would heat his furnace, and as he blew
the bellows to make the flames roar he would curse the thief so that
he would die. And in like manner among these people, with whom
the potters are women, nobody dares to filch anything from a potter;
for next time she heated her wares the potter would curse him,
saying, “Burst like a pot, and may thy house become red,” and the
thief so cursed would die.41.1 In Loango, when a
Charms to protect
property in West
man is about to absent himself from home for a
Africa. considerable time he protects his hut by placing a
charm or fetish before it, consisting perhaps of a
branch with some bits of broken pots or trash of that sort; and we are
told that even the most determined robber would not dare to cross a
threshold defended by these mysterious signs.41.2 On the coast of
Guinea fetishes are sometimes inaugurated for the purpose of
detecting and punishing certain kinds of theft; and not only the culprit
himself, but any person who knows of his crime and fails to give
information is liable to be punished by the fetish. When such a fetish
is instituted, the whole community is warned of it, so that he who
transgresses thereafter does so at his peril. For example, a fetish
was set up to prevent sheep-stealing and the people received
warning in the usual way. Shortly afterwards a slave, who had not
heard of the law, stole a sheep and offered to divide it with a friend.
The friend had often before shared with him in similar enterprises,
but the fear of the fetish was now too strong for him; he informed on
the thief, who was brought to justice and died soon after of a
lingering and painful disease. Nobody in the country ever doubted
but that the fetish had killed him.41.3 Among the Ewe-speaking tribes
of the Slave Coast in West Africa houses and household property
are guarded by amulets (võ-sesao), which derive their virtue from
being consecrated or belonging to the gods. The crops, also, in
solitary glades of the forest are left under the protection of such
amulets, generally fastened to long sticks in some conspicuous
position; and so guarded they are quite safe from pillage. By the side
of the paths, too, may be seen food and palm-wine lying exposed for
sale with nothing but a charm to protect them; a few cowries placed
on each article indicate its price. Yet no native would dare to take the
food or the wine without depositing its price; for he dreads the
unknown evil which the god who owns the charm would bring upon
him for thieving.42.1 In Sierra Leone charms, called greegrees, are
often placed in plantations to deter people from stealing, and it is
said that “a few old rags placed upon an orange tree will generally,
though not always, secure the fruit as effectually as if guarded by the
dragons of the Hesperides. When any person falls sick, if, at the
distance of several months, he recollects having stolen fruit, etc., or
having taken it softly as they term it, he immediately supposes
wangka has caught him, and to get cured he must go or send to the
person whose property he had taken, and make to him whatever
recompense he demands.”42.2
Superstitions of the same sort have been
Charms to protect transported by the negroes to the West Indies,
property in the West
Indies. where the name for magic is obi and the magician
is called the obeah man. There also, we are told,
the stoutest-hearted negroes “tremble at the very sight of the ragged
bundle, the bottle or the egg-shells, which are stuck in the thatch or
hung over the door of a hut, or upon the branch of a plantain tree, to
deter marauders.… When a negro is robbed of a fowl or a hog, he
applies directly to the Obeah-man or woman; it is then made known
among his fellow blacks, that obi is set for the thief; and as soon as
the latter hears the dreadful news, his terrified imagination begins to
work, no resource is left but in the superior skill of some more
eminent Obeah-man of the neighbourhood, who may counteract the
magical operations of the other; but if no one can be found of higher
rank and ability; or if, after gaining such an ally, he should still fancy
himself affected, he presently falls into a decline, under the incessant
horror of impending calamities. The slightest painful sensation in the
head, the bowels, or any other part, any casual loss or hurt, confirms
his apprehensions, and he believes himself the devoted victim of an
invisible and irresistible agency. Sleep, appetite and cheerfulness
forsake him; his strength decays, his disturbed imagination is
haunted without respite, his features wear the settled gloom of
despondency: dirt, or any other unwholesome substance, becomes
his only food, he contracts a morbid habit of body, and gradually
sinks into the grave.”43.1 Superstition has killed him.
Similar evidence might doubtless be multiplied,
Conclusion. but the foregoing cases suffice to shew that
among many peoples and in many parts of the
world superstitious fear has operated as a powerful motive to deter
men from stealing. If that is so, then my second proposition may be
regarded as proved, namely, that among certain races and at certain
times superstition has strengthened the respect for private property
and has thereby contributed to the security of its enjoyment.
IV.
MARRIAGE

I pass now to my third proposition, which is, that


Superstition as a among certain races and at certain times
prop of sexual
morality. superstition has strengthened the respect for
marriage, and has thereby contributed to a stricter
observance of the rules of sexual morality both among the married
and the unmarried. That this is true will appear, I think, from the
following instances.
Among the Karens of Burma “adultery, or
Adultery or fornication, is supposed to have a powerful
fornication
supposed by the influence to injure the crops. Hence, if there have
Karens to blight the been bad crops in a village for a year or two, and
crops. the rains fail, the cause is attributed to secret sins
of this character, and they say the God of heaven
and earth is angry with them on this account; and all the villagers
unite in making an offering to appease him.” And
Pig’s blood used to when a case of adultery or fornication has come to
expiate the crime.
light, “the elders decide that the transgressors
must buy a hog, and kill it. Then the woman takes one foot of the
hog, and the man takes another, and they scrape out furrows in the
ground with each foot, which they fill with the blood of the hog. They
next scratch the ground with their hands and pray: ‘God of heaven
and earth, God of the mountains and hills, I have destroyed the
productiveness of the country. Do not be angry with me, do not hate
me; but have mercy on me, and compassionate me. Now I repair the
mountains, now I heal the hills, and the streams and the lands. May
there be no failure of crops, may there be no unsuccessful labours,
or unfortunate efforts in my country. Let them be dissipated to the
foot of the horizon. Make thy paddy fruitful, thy rice abundant. Make
the vegetables to flourish. If we cultivate but little, still grant that we
may obtain a little.’ After each has prayed thus, they return to the
house and say they have repaired the earth.”45.1 Thus, according to
the Karens adultery and fornication are not simply moral offences
which concern no one but the culprits and their families: they
physically affect the course of nature by blighting the earth and
destroying its fertility; hence they are public crimes which threaten
the very existence of the whole community by cutting off its food
supplies at the root. But the physical injury which these offences do
to the soil can be physically repaired by saturating it with pig’s blood.
Some of the tribes of Assam similarly trace a
Disastrous effects connexion between the crops and the behaviour of
ascribed to sexual
crime in Assam, the human sexes; for they believe that so long as
Bengal, and the crops remain ungarnered, the slightest
Annam.
incontinence would ruin all.45.2 Again, the
inhabitants of the hills near Rajamahal in Bengal imagine that
adultery, undetected and unexpiated, causes the inhabitants of the
village to be visited by a plague or destroyed by tigers or other
ravenous beasts. To prevent these evils an adulteress generally
makes a clean breast. Her paramour has then to furnish a hog, and
he and she are sprinkled with its blood, which is supposed to wash
away their sin and avert the divine wrath. When a village suffers from
plague or the ravages of wild beasts, the people religiously believe
that the calamity is a punishment for secret immorality, and they
resort to a curious form of divination to discover the culprits, in order
that the crime may be duly expiated.45.3 The Khasis of Assam are
divided into a number of clans which are exogamous, that is to say,
no man may marry a woman of his own clan. Should a man be found
to cohabit with a woman of his own clan, it is treated as incest and is
believed to cause great disasters; the people will be struck by
lightning or killed by tigers, the women will die in child-bed, and so
forth. The guilty couple are taken by their clansmen to a priest and
obliged to sacrifice a pig and a goat; after that they are made
outcasts, for their offence is inexpiable.46.1 The Orang Glai, a savage
tribe in the mountains of Annam, similarly suppose that illicit love is
punished by tigers, which devour the sinners. If a girl is found with
child, her family offers a feast of pigs, fowls, and wine to appease the
offended spirits.46.2
The Battas of Sumatra in like manner think that if an unmarried
woman is with child, she must be given in marriage at once, even to
a man of lower rank; for otherwise the people will
Similar views held be infested with tigers, and the crops in the fields
by the Battas of
Sumatra. will not be abundant. They also believe that the
adultery of married women causes a plague of
tigers, crocodiles, or other wild beasts. The crime of incest, in their
opinion, would blast the whole harvest, if the wrong were not
speedily repaired. Epidemics and other calamities that affect the
whole people are almost always traced by them to incest, by which is
to be understood any marriage that conflicts with their customs.46.3
The natives of Nias, an island to the west of Sumatra, imagine that
heavy rains are caused by the tears of a god weeping at the
commission of adultery or fornication. The punishment for these
crimes is death. The two delinquents, man and woman, are buried in
a narrow grave with only their heads projecting above ground; then
their throats are stabbed with a spear or cut with a knife, and the
grave is filled up. Sometimes, it is said, they are buried alive.
However, the judges are not always incorruptible and the injured
family not always inaccessible to the allurement of gain; and
pecuniary compensation is sometimes accepted as a sufficient salve
for wounded honour. But if the wronged man is a chief, the culprits
must surely die. As a consequence, perhaps, of this severity, the
crimes of adultery and fornication are said to be far less frequent in
Nias than in Europe.47.1
Similar views prevail among many tribes in
Similar views Borneo. Thus in regard to the Sea Dyaks we are
among the tribes of
Borneo. told by Archdeacon Perham that “immorality
among the unmarried is supposed to bring a
plague of rain upon the earth, as a punishment inflicted by Petara. It
must be atoned for with sacrifice and fine. In a
Excessive rains function which is sometimes held to procure fine
thought by the
Dyaks to be caused weather, the excessive rain is represented as the
by sexual offences. result of the immorality of two young people.
Petara is invoked, the offenders are banished from
their home, and the bad weather is said to cease. Every district
traversed by an adulterer is believed to be accursed of the gods until
the proper sacrifice has been offered.”47.2 When rain pours down day
after day and the crops are rotting in the fields, these Dyaks come to
the conclusion that some people have been secretly indulging in
lusts of the flesh; so the elders lay their heads together and
adjudicate on all cases of incest and bigamy, and purify the earth
with the blood of pigs, which appears to these
Blood of pigs shed savages, as sheep’s blood appeared to the
to expiate incest
and unchastity. ancient Hebrews, to possess the valuable property
of atoning for moral guilt. Not long ago the
offenders, whose lewdness had thus brought the whole country into
danger, would have been punished with death or at least slavery. A
Dyak may not marry his first cousin unless he first performs a special
ceremony called bergaput to avert evil consequences from the land.
The couple repair to the water-side, fill a small pitcher with their
personal ornaments, and sink it in the river; or instead of a jar they
fling a chopper and a plate into the water. A pig is then sacrificed on
the bank, and its carcase, drained of blood, is thrown in after the jar.
Next the pair are pushed into the water by their friends and ordered
to bathe together. Lastly, a joint of bamboo is filled with pig’s blood,
and the couple perambulate the country and the villages round
about, sprinkling the blood on the ground. After that they are free to
marry. This is done, we are told, for the sake of the whole country, in
order that the rice may not be blasted by the marriage of cousins.48.1
Again, we are informed that the Sibuyaus, a Dyak tribe of Sarawak,
are very careful of the honour of their daughters, because they
imagine that if an unmarried girl is found to be with child it is
offensive to the higher powers, who, instead of always chastising the
culprits, punish the tribe by visiting its members with misfortunes.
Hence when such a crime is detected they fine the lovers and
sacrifice a pig to appease the angry powers and to avert the
sickness or other calamities that might follow. Further, they inflict
fines on the families of the couple for any severe accident or death
by drowning that may have happened at any time within a month
before the religious atonement was made; for they regard the
families of the culprits as responsible for these mishaps. The fines
imposed for serious or fatal accidents are heavy; for simple wounds
they are lighter. With the fear of these fines before their eyes parents
keep a watchful eye on the conduct of their daughters. Among the
Dyaks of the Batang Lupar river the chastity of the unmarried girls is
not so strictly guarded; but in respectable families, when a daughter
proves frail, they sacrifice a pig and sprinkle its blood on the doors to
wash away the sin.48.2 The Hill Dyaks of Borneo abhor incest and do
not allow the marriage even of cousins. In 1846 the Baddat Dyaks
complained to Mr. Hugh Low that one of their chiefs had disturbed
the peace and prosperity of the village by marrying his own
granddaughter. Since that disastrous event, they said, no bright day
had blessed their territory; rain and darkness alone prevailed, and
unless the plague-spot were removed, the tribe would soon be
ruined. The old sinner was degraded from office, but apparently
allowed to retain his wife; and the domestic brawls between this ill-
assorted couple gave much pain to the virtuous villagers.49.1
Among the pagan tribes of Borneo in general,
Incest punished but of Sarawak in particular, “almost all offences
with death by the
pagan tribes of are punished by fines only. Of the few offences
Borneo. which are felt to require a heavier punishment, the
one most seriously regarded is incest. For this
offence, which is held to bring grave peril to the whole house,
especially the danger of starvation through failure of the padi crop,
two punishments have been customary. If the guilt of the culprits is
perfectly clear, they are taken to some open spot on the river-bank at
some distance from the house. There they are thrown together upon
the ground and a sharpened bamboo stake is driven through their
bodies, so that they remain pinned to the earth. The bamboo, taking
root and growing luxuriantly on this spot, remains as a warning to all
who pass by; and, needless to say, the spot is looked on with horror
and shunned by all men. The other method of punishment is to shut
up the offenders in a strong wicker cage and to throw them into the
river. This method is resorted to as a substitute for the former one,
owing to the difficulty of getting any one to play the part of
executioner and to drive in the stake, for this involves the shedding
of the blood of the community. The kind of incest most commonly
committed is the connection of a man with an adopted daughter, and
(possibly on account of this frequency) this is the kind which is most
strongly reprobated.… The punishment of the incestuous couple
does not suffice to ward off the danger brought by them upon the
community. The household must be purified with the blood of pigs
and fowls; the animals used are the property of the offenders or of
their family; and in this way a fine is imposed. When any calamity
threatens or falls upon a house, especially a great rising of the river
which threatens to sweep away the house or the tombs of the
household, the Kayans are led to suspect that incestuous
intercourse in their own or in neighbouring houses has taken place;
and they look round for evidences of it, and sometimes detect a case
which otherwise would have remained hidden. It seems probable
that there is some intimate relation between this belief and the
second of the two modes of punishment described above; but we
have no direct evidence of such connection. All the other peoples
also, except the Punans, punish incest with death. Among the Sea
Dyaks the most common form of incest is that between a youth and
his aunt, and this is regarded at least as seriously as any other
form.”50.1
Nor is it the heinous crime of incest alone which
Evil and confusion in the opinion of the Sea Dyaks endangers the
supposed by the
Dyaks to be whole community. The same effect is supposed to
wrought by follow whenever an unmarried woman is found
fornication. with child and cannot or will not name her seducer.
“The greatest disgrace,” we are told, “is attached
to a woman found in a state of pregnancy, without being able to
name her husband; and cases of self-poisoning, to avoid the shame,
are not of unusual occurrence. If one be found in this state, a fine
must be paid of pigs and other things. Few even of the chiefs will
come forward without incurring considerable responsibility. A pig is
killed, which nominally becomes the father, for want, it is supposed,
of another and better one. Then the surrounding neighbours have to
be furnished with a share of the fine to banish the Jabu, which exists
after such an event. If the fine be not forthcoming, the woman dare
not move out of her room, for fear of being molested, as she is
supposed to have brought evil (kudi) and confusion upon the
inhabitants and their belongings.”50.2
The foregoing accounts refer especially to the
Similar beliefs and tribes of Borneo under British rule; but similar
customs among the
tribes of Dutch ideas and customs prevail among the kindred
Borneo. tribes of Dutch Borneo. Thus the Kayans or
Bahaus in the interior of the island believe that adultery is punished
by the spirits, who visit the whole tribe with failure of the crops and
other misfortunes. Hence in order to avert these evil consequences
from the innocent members of the tribe, the two culprits, with all their
possessions, are first placed on a gravel bank in the middle of the
river, in order to isolate or, in electrical language, to insulate them
and so prevent the moral or rather physical infection from spreading.
Then pigs and fowls are killed, and with the blood priestesses smear
the property of the guilty pair in order to disinfect it. Finally, the two
are placed on a raft, with sixteen eggs, and allowed to drift down
stream. They may save themselves by plunging into the water and
swimming ashore; but this is perhaps a mitigation of an older
sentence of death by drowning, for young people still shower long
grass stalks, representing spears, at the shamefaced and dripping
couple.51.1 Certain it is, that some Dyak tribes used to punish incest
by fastening the man and woman in separate baskets laden with
stones and drowning them in the river. By incest they understood the
cohabitation of parents with children, of brothers with sisters, and of
uncles and aunts with nieces and nephews. A Dutch resident had
much difficulty in saving the life of an uncle and niece who had
married each other; finally he procured their banishment to a distant
part of Borneo.51.2 The Blu-u Kayans, another tribe in the interior of
Borneo, believe that an intrigue between an unmarried pair is
punished by the spirits with failure of the harvest, of the fishing, and
of the hunt. Hence the delinquents have to appease the wrath of the
spirits by sacrificing a pig and a certain quantity of rice.51.3 In Pasir, a
district of Eastern Borneo, incest is thought to bring dearth,
epidemics, and all sorts of evils on the land.51.4 In the island of
Ceram a man convicted of unchastity has to smear every house in
the village with the blood of a pig and a fowl: this is supposed to wipe
out his guilt and ward off misfortunes from the village.51.5
When the harvest fails in Southern Celebes, the
Failure of the crops Macassars and Bugineese regard it as a sure sign
and other disasters
thought to be that incest has been committed and that the spirits
caused by incest in are angry. In the years 1877 and 1878 it happened
Celebes. that the west monsoon did not blow and that the
rice crop in consequence came to nothing; moreover many buffaloes
died of a murrain. At the same time there was in the gaol at Takalar a
prisoner, who had been formerly accused of incest. Some of the
people of his district begged the Dutch governor to give the criminal
up to them, for according to the general opinion the plagues would
never cease till the guilty man had received the punishment he
deserved. All the governor’s powers of persuasion were needed to
induce the petitioners to return quietly to their villages; and when the
prisoner, having served his time, was released shortly afterwards, he
was, at his own request, given an opportunity of sailing away to
another land, as he no longer felt safe in his own country.52.1 Even
when the incestuous couple has been brought to
Disastrous effects justice, their blood may not be shed; for the people
supposed to follow
from shedding the think that, were the ground to be polluted by the
blood of incestuous blood of such criminals, the rivers would dry up
couples on the and the supply of fish would run short, the harvest
ground.
and the produce of the gardens would miscarry,
edible fruits would fail, sickness would be rife among cattle and
horses, civil strife would break out, and the country would suffer from
other widespread calamities. Hence the punishment of the guilty is
such as to avoid the spilling of their blood: usually they are tied up in
a sack and thrown into the sea to drown. Yet they get on their
journey to eternity the necessary provisions, consisting of a bag of
rice, salt, dried fish, coco-nuts, and other things, among which three
quids of betel are not forgotten.52.2 We can now perhaps understand
why the Romans used to sew up a parricide in a sack with a dog, a
cock, a viper, and an ape for company, and fling him into the sea.
They probably feared to defile the soil of Italy by spilling upon it the
blood of such a miscreant.52.3 Amongst the Tomori of Central
Celebes a person guilty of incest is throttled; no drop of his blood
may fall on the ground, for if it did, the rice would never grow again.
The union of uncle with niece is regarded by these people as incest,
but it can be expiated by an offering. A garment of the man and one
of the woman are laid on a copper vessel; the blood of a sacrificed
animal, either a goat or a fowl, is allowed to drip on the garments,
and then the vessel with its contents is set floating down the river.53.1
Among the Tololaki, another tribe of Central Celebes, persons who
have defiled themselves with incest are shut up in a basket and
drowned. No drop of their blood may be spilt on the ground, for that
would hinder the earth from ever bearing fruit again.53.2 Among the
Bare’e-speaking Toradjas of Central Celebes in general the penalty
for incest, that is for the sexual intercourse of parents with children or
of brothers with sisters, is death. But whereas the death-sentence for
adultery is executed with a spear or a sword, the death-sentence for
incest is usually executed among the inland tribes by clubbing or
throttling; for were the blood of the culprits to drip on the ground, the
earth would be rendered barren. The people on the coast put the
guilty pair in a basket, weight it with stones, and fling it into the sea.
This prescribed manner of putting the incestuous to death, we are
informed, makes the execution very grievous. However, the writers
who furnish us with these particulars and who have lived among the
people on terms of intimacy for many years, add that “incest seldom
occurs, or rather the cases that come to light are very few.”53.3 In
some districts of Central Celebes, the marriage of cousins, provided
they are children of two sisters, is forbidden under pain of death; the
people think that such an alliance would anger the spirits, and that
the rice and maize harvests would fail. Strictly speaking, two such
cousins who have committed the offence should be tied together,
weighted with stones, and thrown into water to drown. In practice,
however, the culprits are spared and their sin expiated by shedding
the blood of a buffalo or a goat. The blood is mixed with water and
sprinkled on the rice-fields or poured on the maize-fields, no doubt in
order to appease the angry spirits and restore its fertility to the tilled
land. The natives of these districts believe that were a brother and
sister to commit incest, the ground on which the tribe dwells would
be swallowed up. If such a crime takes place, the guilty pair are tied
together, their feet weighted with stones, and thrown into the sea.54.1
When it rains in torrents, the Galelareese of
Excessive rains, Halmahera, another large East Indian island, say
earthquakes, and
volcanic eruptions that brother and sister, or father and daughter, or
supposed to be in short some near kinsfolk are having illicit
produced by incest relations with each other, and that every human
in Halmahera.
being must be informed of it, for then only will the
rain cease to descend. The superstition has repeatedly caused blood
relations to be accused, rightly or wrongly, of incest. Further, the
people think that alarming natural phenomena, such as a violent
earthquake or the eruption of a volcano, are caused by crimes of the
same sort. Persons charged with such offences are brought to
Ternate; it is said that formerly they were often drowned on the way
or, on being haled thither, were condemned to be thrown into the
volcano.54.2 In the Banggai Archipelago, to the east of Celebes,
earthquakes are explained as punishments inflicted by evil spirits for
indulgence in illicit love.54.3
In some parts of Africa, also, it is believed that
Breaches of sexual breaches of sexual morality disturb the course of
morality thought to
blight the fruits of nature, particularly by blighting the fruits of the
the earth and earth; and probably such views are much more
otherwise disturb widely diffused in that continent than the scanty
the course of nature
in Africa. and fragmentary evidence at our disposal might
lead us to suppose. Thus, the negroes of Loango,
in West Africa, imagine that the commerce of a man with an
immature girl is punished by God with drought and consequent
famine until the transgressors expiate their transgression by dancing
naked before the king and an assembly of the people, who throw hot
gravel and bits of glass at the pair as they run the gauntlet. The rains
in that country should fall in September, but in 1898 there was a long
drought, and when the month of December had nearly passed, the
sun-scorched stocks of the fruitless Indian corn shook their rustling
leaves in the wind, the beans lay shrivelled and black on the ruddy
soil, and the shoots of the sweet potato had flowered and withered
long ago. The people cried out against their rulers for neglecting their
duty to the primeval powers of the earth; the priests of the sacred
groves had recourse to divination and discovered that God was
angry with the land on account of the immorality of certain persons
unknown, who were not observing the traditions and laws of their
God and country. The feeble old king had fled, but the slave who
acted as regent in his room sent word to the chiefs that there were
people in their towns who were the cause of God’s wrath. So every
chief called his subjects together and caused enquiries to be made,
and then it was discovered that three girls had broken the customs of
their country; for they were with child before they had passed
through what is called the paint-house, that is, before they had been
painted red and secluded for a season in token that they had
attained to the age of puberty. The people were incensed and
endeavoured to punish or even kill the three girls; and the English
writer who has recorded the case has thought it worth while to add
that on the very morning when the culprits were brought before the
magistrate rain fell.55.1 Amongst the Bavili of Loango, who are
divided into totemic clans, no man is allowed to marry a woman of
his mother’s clan; and God is believed to punish a breach of this
marriage law by withholding the rains in their due season.56.1 Similar
notions of the blighting influence of sexual crime appear to be
entertained by the Nandi of British East Africa; for we are told that
when a warrior has got a girl with child, she “is punished by being put
in Coventry, none of her girl friends being allowed to speak to or look
at her until after the child is born and buried. She
Sexual purity is also regarded with contempt for the rest of her
required of those
who handle corn or life and may never look inside a granary for fear of
enter a granary. spoiling the corn.”56.2 Among the Basutos in like
manner “while the corn is exposed to view, all
defiled persons are carefully kept from it. If the aid of a man in this
state is necessary for carrying home the harvest, he remains at
some distance while the sacks are filled, and only approaches to
place them upon the draught oxen. He withdraws as soon as the
load is deposited at the dwelling, and under no pretext can he assist
in pouring the corn into the basket in which it is preserved.”56.3 The
nature of the defilement which thus disqualifies a man from handling
the corn is not mentioned, but we may conjecture that unchastity
would fall under this general head. For amongst the Basutos after a
child is born a fresh fire has to be kindled in the dwelling by the
friction of wood, and this must be done by a young man of chaste
habits; it is believed that an untimely death awaits him who should
dare to discharge this holy office after having lost his innocence.56.4
In Morocco whoever enters a granary must first remove his slippers
and must be sexually clean. Were an unclean person to enter, the
people believe not only that the grain would lose its blessed
influence (baraka), but that he himself would fall ill. A Berber told Dr.

You might also like