gython
gython

Reputation: 875

Recursive value chain0 needs type

I have two variants of the same function chain in Scala:

type IntFun = Int => Int

val compose = (f: IntFun, g: IntFun) => (i: Int)
  => {
    f(g(i))

val chain: (Int, IntFun) => IntFun =
    (n,f) => {
          if (n == 1) f
    else compose(f, chain(n-1, f))
  }
val chain0 = (n:Int, f:IntFun) =>
    {
      if (n==1) f else compose(f, chain0(n-1, f))
    }

If I try the second variant I get this error:

recursive value chain0 needs type
      if (n==1) f else compose(f, chain0(n-1, f))

What does this error mean?

My guess: Is it mandatory to define a result type in Scala when working with recursion?

Upvotes: 0

Views: 656

Answers (1)

Suma
Suma

Reputation: 34453

It is mandatory to define a result type in Scala whenever the expression is recursive, which is what the error says.

You need to provide a type whenever the variable for which the type is inferred is referenced inside of the expression from which you are inferring the type. In your case val chain0 is defined using chain0, therefore you need to provide a complete variable type.

Inferring type of following expression is impossible in a general case with chain0 type not known yet:

if (n==1) f else compose(f, chain0(n-1, f))

Note: Scala compiler requires you to always specify a type for a recursive value, even in cases where the type could be inferred easily, like in the following case:

val foo = {
  val x = foo
  0
}

It is safer for the specification to be be a little bit stricter than necessary, this helps keeping the compiler simple by not having to deal with corner cases. A similar situation is you need to provide return types when you use the return keyword.

Upvotes: 4

Related Questions