# Simple Scala Methods for finding Sum and Maximum

I am learning Scala. I have been confronted with the simple task of creating functions for finding the sum and maximum in the list of numbers. A precondition is that both functions should be solved recursively.

There are at least two different ways how to solve each function. First, I tried to come up with a recursive approach in the purest possible form.

Sum function

``````def sum(xs: List[Int]): Int = {
if (xs.isEmpty) {
0
} else {
}
}``````

Max function

``````def max(xs: List[Int]): Int = {
if (xs.isEmpty) {
throw new NoSuchElementException
} else {
if (xs.tail.isEmpty) {
}
val tailMax = max(xs.tail)
} else {
tailMax
}
}
}``````

After that, I searched for the correct answer on the web. However, I remembered that Scala offers pattern matching through something called `match expressions`. Therefore, it is better to say it is like advanced switch statements, a feature lacking in older versions of Java.

Sum function

``````def sum(xs: List[Int]): Int = xs match {
case List() => 0
case _ => xs.head + sum(xs.tail)
}``````

Max function

``````def max(xs: List[Int]): Int = xs match {
case List() => throw new java.util.NoSuchElementException
case x :: Nil => x
case _ => val tailMax: Int = max(xs.tail);