2

This non compiling code on defining a recursive function value,

val factorial = (n:Int) => if (n < 1) 1 else n * factorial(n-1)

produces an error message such as

recursive value factorial needs type

How to declare the return type ?

2 Answers 2

8

Like this

val factorial: Int => Int = (n:Int) => if (n<1) 1 else n*factorial(n-1)

In fact, I would write it like so:

def factorial(n: Int): Int = if (n < 1) 1 else n * factorial(n-1)
Sign up to request clarification or add additional context in comments.

Comments

3
val factorial: Int => Int = (n) => if (n<1) 1 else n*factorial(n-1)

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.