How to create a list with n the same elements in Scala ?

Thanks to the withDefault(...) method, Scala has a very easy practical and easy way to define the default value for a key not present in the map. Unfortunately, the sequences don't benefit from this behavior. We can see this in the case of a fixed-length sequence containing the same value at every position. With a kind of "with-default" method, we could write it as:

val aLetter = (0 until 100).withDefault("a")

But it's not the case. Fortunately, Scala is pretty flexible and lets us implement this feature in many different ways. The simplest is the most intuitive one consists on the use of fill(...) method that, as you can guess, fills a sequence with the specified value:

  behavior of "a sequence"
  it should "contain the same elements put with a fill method" in {
    val aLetterSequence = Seq.fill(100)("a")

    aLetterSequence should have size 100
    aLetterSequence should contain only ("a")
  }

Apart from that, we can use the methods based on the iteration and mapping::
  it should "contain the same elements put with a map" in {
    val aLetterSequence = (0 until 100).map(_ => "a")

    aLetterSequence should have size 100
    aLetterSequence should contain only ("a")
  }

  it should "contain the same elements put with iterate method" in {
    val aLetterSequence = Seq.iterate("a", 100)(_ => "a")

    aLetterSequence should have size 100
    aLetterSequence should contain only ("a")
  }
  it should "contain the same elements put with a tabulate method" in { 
    val aLetterSequence = Seq.tabulate(100)(_ => "a")

    aLetterSequence should have size 100
    aLetterSequence should contain only ("a")
  }