Book Image

Scala Design Patterns

By : Ivan Nikolov
Book Image

Scala Design Patterns

By: Ivan Nikolov

Overview of this book

Scala has become increasingly popular in many different IT sectors. The language is exceptionally feature-rich which helps developers write less code and get faster results. Design patterns make developer’s lives easier by helping them write great software that is easy to maintain, runs efficiently and is valuable to the company or people concerned. You will learn about the various features of Scala and be able to apply well-known, industry-proven design patterns in your work. The book starts off by focusing on some of the most interesting features of Scala while using practical real-world examples. We will also cover the popular "Gang of Four" design patterns and show you how to incorporate functional patterns effectively. By the end of this book, you will have enough knowledge and understanding to quickly assess problems and come up with elegant solutions.
Table of Contents (20 chapters)
Scala Design Patterns
Credits
About the Author
Acknowledgments
About the Reviewer
www.PacktPub.com
Preface
Index

The iterator design pattern


We use iterators in software projects all the time. When we traverse a list or go through the items of a set or a map, we use an iterator.

Note

The iterator design pattern provides a way to access the elements of an aggregate object (collection) in a sequential manner without exposing the underlying representation of the items. The developer doesn't need to know whether there is a linked list, array, tree, or a hash map underneath.

Class diagram

Using the iterator design pattern, we can create our own objects that act as collections and we can use them in the foreach loops. In Java, there is an interface called Iterator, which we can implement for this purpose. In Scala, we can mix in the Iterator trait and implement its hasNext and next methods.

For the class diagram and the example, let's have a ClassRoom class that will support a foreach loop running through all students. The following figure shows our class diagram:

We've decided our ClassRoom class to implement...