To append or prepend one or more elements to a
Seq, use these methods:
As a brief Scala tip, a fun thing you can do with the
map method on Scala sequences (
Vector, etc.) is to convert a sequence of objects into a sequence of something else, typically extracting a field from the original object to create the new sequence.
For instance, imagine that you have a case class named
Person that has two constructor parameters,
“Every person in your company is a vector. Your progress is determined by the sum of all vectors.”
That’s a quote from Elon Musk. In this context a vector is what I know about from my engineering background, a company of both a speed and a direction, something like this:
case class Vector(speed: Double, direction: String)
The correct thing about that quote is that the worst employees I ever had pulled in a direction that was somewhere around 180 degrees opposite of the direction we were aiming for. For example, if nine out of ten employees are rowing a boat that’s headed east, an employee that’s rowing towards the west is going to slow everyone else down.
Unfortunately I never had much success turning those people around, so they were always fired or encouraged to find other work. Over the years we had everything from people whose work had to be completely re-done to people who had agendas during the 8-5 work hours that had nothing to do with the company’s agenda.
When I wrote the Scala Cookbook, I gave each recipe and then each chapter my full attention. I thought that if I wrote each recipe as well as possible, and included important recipes in each chapter, well, I wanted each chapter to be worth the price of the entire book. That was my goal.
As a result of this effort -- and perhaps to the chagrin of my editor -- the Scala collections chapters ended up being 130 pages in length.
As a brief note, I knew that the
sum function I wrote in my book on Scala and functional programming would return a wrong value if the sum of the integers in a list was greater than
Int.MaxValue, and I was curious how the built-in
sum method on lists handled the same problem. It turns out that it works in the same way.
So, if you need to sum a list of integers that may exceed
Int.MaxValue, you might need to write a sum function that calculates and returns the sum as a
Long. (The same is true for
As a quick note, if you ever need to fill/populate a Scala list with the same element X number of times, one solution is to use the
fill method that’s available to Scala sequences, like this:
scala> val x = List.fill(3)("foo") x: List[String] = List(foo, foo, foo)
If you want to populate a list with different element values, another approach is to use the