Search⌘ K

Challenge: Sum of Lists

Explore how to create a recursive function in Scala that computes the sum of integers in a list. Understand the use of pattern matching in recursion and prepare to review alternate solutions for deeper insights.

Problem Statement

In this challenge, you need to create a recursive function sum which returns the total sum of the integers in a List.

The provided skeleton code uses match and you are required to use the skeleton code. However, there is an alternate solution to this problem which we will discuss in the solution review.

Input

The input of the function is a List of integers numberList.

Output

The output will be the sum of all the integer in numberList.

Sample Input

List(1,2,3,4,5)

Sample Output

15

Test Yourself

Write your code in the given area. Try the exercise by yourself first, but if you get stuck, the solution has been provided. Good luck!

Scala
def sum(numberList: List[Int]): Int = numberList match {
// Write your code here
case _ => -1 // Remove this line after writing your code
}

Let’s go over the solution review in the next lesson.