Skip to content

Instantly share code, notes, and snippets.

@jimleroyer
Last active August 29, 2015 14:01
Show Gist options
  • Save jimleroyer/ef653a2307fda123317c to your computer and use it in GitHub Desktop.
Save jimleroyer/ef653a2307fda123317c to your computer and use it in GitHub Desktop.
import scala.annotation.tailrec
/**
* To compile and look at the generated Java bytecode of this class, execute
* these commands at the command-line prompt:
*
* > scalac tailrec.scala
* > javap -p -c Test$.class
*
* This is of value to observe the differences in the generated bytecode by
* the Scala compiler for tail recursive methods versus non-tail versus
* by-name param versus by-value param. This is discussed at length in the
* discussion forum for the Scala class "Functional Programming Principles
* in Scala" at this link:
* https://class.coursera.org/progfun-004/forum/thread?thread_id=162
*/
object Test {
@tailrec final def tailRec(x: Int): Int = if (x == 0) x else tailRec(x - 1)
final def nonTailRec(x: Int): Int = if (x == 0) x else nonTailRec(x) - 1
final def nonTailRecAndByNameArgs(x: => Int): Int = if (x == 0) x else nonTailRecAndByNameArgs(x) - 1
@tailrec final def tailRecAndByNameArg(x: => Int): Int = if (x == 0) x else tailRecAndByNameArg(x - 1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment