elm
elm

Reputation: 20435

Scala recursive function values definition

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 ?

Upvotes: 2

Views: 1965

Answers (2)

om-nom-nom
om-nom-nom

Reputation: 62855

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)

Upvotes: 8

Ionuț G. Stan
Ionuț G. Stan

Reputation: 179219

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

Upvotes: 3

Related Questions