Skip to content
Create a gist now

Instantly share code, notes, and snippets.

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
import annotation.tailrec
object TailRec {
// A tail-recursive function, from
@tailrec def isDivis(x:Int, i:Int):Boolean =
if(i > 20) true
else if(x % i != 0) false
else isDivis(x, i+1)
// The same code, written using && and || (in a more readable way):
// since && and || are short-circuiting, this code means the same
// thing. So much the same that isDivis2 is also tail-recursive.
@tailrec def isDivis2(x: Int, i: Int): Boolean =
(i > 20) || (x % i == 0) && isDivis2(x, i+1)
// I compared the generated bytecode, and noticed that there is a
// minor difference - similar to the difference between if (cond)
// branch1 branch2 and if (!cond) branch2 branch1, that is the order
// of branches is different.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.