How to generate tuples from Scala's sequence ?

Scala's collection have a lot of interesting methods like grouped, take and drop. Another one that I didn't know was sliding. It behaves like a sliding window, i.e. it always takes X elements where the X-1 come from the previous block:

"sliding of 3 for 7-elements sequence" should "return 5 sliding blocks" in {
  val letters = Seq("a", "b", "c", "d", "e", "f", "g")

  val slidingBlocks = letters.sliding(3).toSeq

  slidingBlocks should have size 5
  slidingBlocks should contain allOf(Seq("a", "b", "c"), Seq("b", "c", "d"), Seq("c", "d", "e"), Seq("d", "e", "f"),
    Seq("e", "f", "g"))
}

How to apply a different transformation for the last element of a sequence in Scala ?

Mapping Scala's sequence elements is easy when the mapping logic is the same for all items. However, sometimes you may want to apply different transformation to the first or the last element of the list. Doing this with .map is possible but before you will need to zip the sequence to generate the indexes.

Fortunately, tails and collect's partial function are a less verbose alternative:

"the last element" should "be mapped differently" in {
  val letters = Seq("a", "b", "c", "d", "e", "f", "g")

  val mappedLetters = letters.tails.collect {
      case Seq(firstElement, _, _*) => firstElement.toUpperCase()
      case Seq(lastElement) => s"${lastElement.toUpperCase()}${lastElement.toUpperCase()}"
  }.toList

  mappedLetters should have size 7
  mappedLetters should contain inOrderElementsOf(Seq("A", "B", "C", "D", "E", "F", "GG"))
}