Reputation: 221
When creating a function with recursion on Pattern matching its throws the below error, but when created with a method it works fine. Can you please help me understand.
val power: (Int, Int) => Int = (base: Int, exp: Int) => {
exp match {
case 0 => 1
case 1 => `base`
case e => `base` * power(`base`, e - 1)
}
}
The code above shows produces the error: "Forward reference extends over definition of value". But the code below works fine:
def func1(base: Int, exp: Int): Int = {
exp match {
case 0 => 1
case 1 => `base`
case e => `base` * func1(`base`, e - 1)
}
}
Upvotes: 1
Views: 144
Reputation: 11508
Try adding lazy
to the front of the val
in order that the expression is set rather than executed. Then when it is executed by calling it, it will already have been set.
Upvotes: 2