1

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)
    }
}
2
  • I got the error when i tried to run it via Eclipse Scala Worksheet,but the same code works fine on scala REPL.Thanks jwvh Commented Jul 3, 2015 at 23:53
  • I've tested it on a Scala worksheet on IntelliJ IDEA 14 and 15EAP. It works so I guess it's just Eclipse Scala worksheet issue. Commented Jul 4, 2015 at 6:14

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.