Recursive methods in Scala

Get started functional programming in Scala.

There is a lot of debates about functional programming vs object oriented programming. This post we will not discuss such thing. Instead we just go over how to do simple recursive functions in Scala.

In Object Oriented Programming, we usually mutate the value and therefore we often go with for loop or while loop. In functional programming, we will not use loops, instead we use recursive methods.

For example if we want to sum all the integers in the list, we can do like:

Or if we want to find the max value from the list:

Write some test to verify the methods

@Test def `sum of a few numbers (10pts)`: Unit = {
assert(sum(List(1,2,0)) == 3)

@Test def `max of a few numbers (10pts)`: Unit = {
assert(max(List(3, 7, 2)) == 7)

Alright that’s it.

Happy coding guys.

Thanks for reading my post.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store