Search⌘ K
AI Features

Solution Review: Appending an Element to a List

Explore how to append an element to a Scala list by using the append operator :+. Understand how to access and add elements dynamically to lists within Scala's collection framework, reinforcing your grasp of working with immutable lists in functional programming.

We'll cover the following...

Task

In this challenge, you were provided a list. Your task was to append an element to the list having the same value as the first element of the same list.

Solution

The task required you to use the append List operator :+ which appends an element to the end of a list. The operator has two operands:

  • The first operand is the list to which you wish to append an element.
  • The second operator is the element you wish to append to the end of a list.

In our case, the first operand would be list and the second operand would be list(0). list(0) is accessing the first element of list.

You can find the complete solution below:

You were required to write the code on line 2.

Scala
val list = List("a","b","c")
val finalList = list :+ list(0)
// Driver Code
finalList.foreach(println)

In the next lesson, we will move on to vectors.