Solution Review: Sum of Lists

In the following lesson, we will go over the solution of the challenge: Sum of Lists.

We'll cover the following


In this challenge, you had to create a recursive function sum which sums together all the integers in a List.


A skeleton of the function was already provided for you. Let’s look it over.

def sum(numberList: List[Int]): Int = numberList match { 


sum takes a single parameter of type List[Int] and returns a value of type Int.

The function body of sum consists of a match expression. You needed to write the cases required for sum to execute correctly. The first case would be our base case which is if the List is empty. In this case, sum would return 0.

case Nil => 0

The second case is if the List is not empty. In this case, we separate the first element of the List from the rest of the elements using the built-in :: operator. Let’s see how it will work

case x :: tail

Here the x will contain the first element of the list and the tail will have all the element of the list except the first element (x). Then we will recursively pass the tail (a list) to the sum() method.

case x :: tail => sum(tail)

We will continue this process until the base case is reached i.e., the tail list becomes empty.

You can find the complete solution below:

You were required to write the code from line 1 to line 4.

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy