Recursion is a method which breaks the problem into smaller subproblems and calls itself for each of the problems. That is, it simply means function calling itself. The tail recursive functions better than non tail recursive functions because tail-recursion can be optimized by compiler. A recursive function is said to be tail recursive if the recursive call is the last thing done by the function. There is no need to keep record of the previous state.
For tail recursion function a package
import scala.annotation.tailrec will be used in the program.
@tailrec def FuntionName(Parameter1, Parameter2, ...): type = …
Let us understand tail recursion by examples.
As we can see in above example
@tailrec is used for gcd function that is tail recursion function. By using tail recursion no need to keep record of the previous state of gcd function.
In the above code, we can use the
@tailrec annotation to confirm that our algorithm is tail recursive.
If we use this annotation and our algorithm isn’t tail recursive, the compiler will complain. For instance, if we attempt to use this annotation on the above example of the factorial method, we will get the following compile-time error.
Could not optimize @tailrec annotated method factorial: it contains a recursive call not in tail position.
- Scala TreeSet tail() method with example
- Scala Map tail() method with example
- Scala Set tail() method with example
- Scala Queue tail() method with example
- Scala SortedSet tail() method with example
- Scala Stack tail() method with example
- Scala SortedMap tail() method with example
- Scala Mutable SortedSet tail() method
- Scala Mutable SortedMap tail() method with example
- Recursion in Scala
- Scala Tutorial – Learn Scala with Step By Step Guide
- Scala short <(x: Short): Boolean
- Scala short <(x: Char): Boolean
- Scala Extractors
- Scala | Partially Applied functions
- Scala String indexOf(String str) method with example
- Scala String contentEquals() method with example
- Scala Keywords
- Scala Int /(x: Int) method with example
- Scala Int /(x: Short) method with example
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.