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")) }