I stumbed on the link below which shows how funny scala messages can be 😉
Scala REPL “She’s gone rogue” error message
When i tried this example, it hung forever.what is happening here?
Is this a known bug?Is it some kind of gotcha?
Welcome to Scala version 2.9.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_29
).
Type in expressions to have them evaluated.
Type :help for more information.
scala> def factorial(n: Int):Int = {
| if (n == 1) n // forgot 'return' here
| factorial(n - 1)
| }
factorial: (n: Int)Int
scala> factorial(10)
The problem is exactly what is indicated in the code,
returnis missing. The recursion never terminates.factorial(n - 1)is not connected to theifstatement in any way. This means, that it executes unconditionally.factorial()wil always call itself.Adding a base case (i.e. where the recursion stops):
This would work as well:
This will actually produce the factorial of n (the others return 1):
Note that this works for the case
n = 0correctly as well. It still accepts negative numbers, however.