fill

Scala ArrayBuffer class: methods, syntax, and examples alvin August 16, 2018 - 12:33pm

This page contains a large collection of examples of how to use the Scala ArrayBuffer class.

Use the ArrayBuffer class when you want to use a general-purpose, mutable indexed sequence in your Scala applications:

Scala Array class: methods, examples, and syntax alvin June 16, 2018 - 5:09pm

This page contains a large collection of examples of how to use the methods on the Scala Array class.

Scala List class: methods, examples, and syntax alvin May 22, 2018 - 1:00pm

This page contains a large collection of examples of how to use the methods on the Scala List class.

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 filter, map, foldLeft, reduceLeft.

Scala Seq class: methods, examples, and syntax

This page contains a large collection of examples of how to use the methods on the Scala Seq class.

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 IndexedSeq or LinearSeq where appropriate. As the Seq class Scaladoc states:

Scala: How to fill/populate a list (same element or different elements)

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 tabulate method:

Scala functions to repeat a character n times (blank padding)

Earlier today I needed a function that would return a desired number of blank spaces so I could “pad” some output as desired. For some reason my mind went blank and I forgot about using a printf-style solution, and it quickly went to, “How can I write a Scala function to return n number of blank spaces?”

Note: If you just want the “best” solution, please scroll to the bottom of this article.

Different ways to create and populate Lists in Scala

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 11.1, “Different Ways to Create and Populate a List in Scala”

Problem

You want to create and populate a List.

Solution

There are many ways to create and initially populate a List: