Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 516
elm Avatar asked Dec 14 '25 00:12

elm


1 Answers

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)
like image 162
om-nom-nom Avatar answered Dec 15 '25 20:12

om-nom-nom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!