Reputation: 31543
I would like the compiler to warn me when it applies tail recursion to one of my functions when I haven't told it to with the annotation. Is this possible?
Motivation: I very rarely write infinite loops as a matter of logic error, but I have done with typos (yes it is possible). Usually recursive infinite loops just tell you what is wrong with a stack overflow exception, but not if they get compiled tail recursively, it just hangs.
Forgetting the new
keyword in combination with case classes with default params is a good example that I have foolishly stumbled on twice:
case class A(a: Int, b: Int = 1)
object A {
def apply(a: Int): A = A(a)
Causes an infinite loop with no SO, but def apply(a: Int): A = new A(a)
does not
Upvotes: 2
Views: 441
Reputation: 40510
Avoid declaring function return types when practical: def apply(a: Int) = A(a)
would fail to compile, so you would know that something is wrong.
Upvotes: 0
Reputation: 37461
I don't think the compiler has this but IntelliJ offers a "No tail recursion annotation" under Inspections > Scala: General
Detects tail recursive methods without @tailrec annotation which verifies that the method will be compiled with tail call optimization.
Upvotes: 3