Reader small image

You're reading from  Learning Scala Programming

Product typeBook
Published inJan 2018
Reading LevelBeginner
PublisherPackt
ISBN-139781788392822
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Vikash Sharma
Vikash Sharma
author image
Vikash Sharma

Vikash Sharma is a software developer and open source technology evangelist. He tries to keep things simple, which helps him write clean and manageable code. He has invested a large amount of time learning and implementing Scala code, and he has authored video courses for Scala. He works as a developer at SAP Labs.
Read more about Vikash Sharma

Right arrow

Recursion


Recursion is a function's call to itself. In simple words, a recursive function is a function which calls itself. Functional programming recommends use of recursion over the use of iterative looping constructs. For the same obvious reasons, Scala also recommends use of recursion. Let's first take a look at a recursive function:

object RecursionEx extends App {

   /*
   * 2 to the power n
   * only works for positive integers!
   */
 def power2toN(n: Int): Int = if(n == 0) 1 else 2 * power2toN(n - 1)

   println(power2toN(2))
   println(power2toN(4))
   println(power2toN(6))
 } 

The following is the result:

4 
16 
64 

We've defined a function power2toN which expects an integer n, checks for n value and if it's not 0, the function calls itself, decrementing n integer's value till the number n becomes 0. Then comes multiplying the value with 2 with each recursive call to get the desired result.

Consider the following:

def power2toN(n: Int) = if(n == 0) 1 else (2 * power2toN(n - 1)) 

The...

lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Learning Scala Programming
Published in: Jan 2018Publisher: PacktISBN-13: 9781788392822

Author (1)

author image
Vikash Sharma

Vikash Sharma is a software developer and open source technology evangelist. He tries to keep things simple, which helps him write clean and manageable code. He has invested a large amount of time learning and implementing Scala code, and he has authored video courses for Scala. He works as a developer at SAP Labs.
Read more about Vikash Sharma