The Scala List class as an immutable, linear, linked-list class. It’s very efficient when it makes sense for your algorithms to (a) prepend all new elements, (b) work with it in terms of its head and tail elements, and (c) use functional methods that traverse the list from beginning to end, such as
Important note about Seq, IndexedSeq, and LinearSeq
As an important note, I use
Seq in the following examples to keep things simple, but in your code you should be more precise and use
LinearSeq where appropriate. As the
Seq class Scaladoc states:
Last night I was reading the classic old book, The Pragmatic Programmer, and came across this definition of DRY, an acronym that stands for Don’t Repeat Yourself:
“Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.”
That’s well stated, especially after a recent experience in which I found some code where I created an “Add Widget” dialog in a different way than I created its related “Edit Widget” dialog. I created the main pane of the dialog the same way, but I managed the details of the two dialogs that contained that pane differently, and I realized what I had done when I decided to make the dialog resizable. When I discovered what I had done, I refactored the code so both the Add and Edit dialogs were created by a single method.
As a quick note, this is the syntax for creating a Scala
import scala.collection.mutable.ArrayBuffer val fruits = ArrayBuffer[String]() val ints = ArrayBuffer[Int]()
The key thing to know is that the keyword
new is not required before the
ArrayBuffer. (This is because
ArrayBuffer is either defined as a case class, or because it has an apply method defined. I haven’t looked at its source code to know which approach is taken.)
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 11.26, “How to Add Elements to a Set in Scala”
You want to add elements to a mutable set, or create a new set by adding elements to an immutable set.
Mutable and immutable sets are handled differently, as demonstrated in the following examples.
Add elements to a mutable
Set with the
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 11.16, “How to Add, Update, and Remove Elements with Immutable Maps”
You want to add, update, or delete elements when working with an immutable map.
Use the correct operator for each purpose, remembering to assign the results to a new map.
To be clear about the approach, the following examples use an immutable map with a series of
val variables. First, create an immutable map as a