Gary Sieling

Fixing scala error “error: recursive value count needs type”

If you try to define a recursive function without a type, you will get this error:

error: recursive value count needs type

For example, note how this “count” value doesn’t have a type:

val count = 
  (values: Seq[Any]) => { 
    values.headOption match { 
      case Some(_) => 1 + count(values.tail) 
      case None => 0 
    }
  }

The fix is fairly simple (although the type is hard to read):

val count: (Seq[Any]) => Int = 
  ...

I found in doing this that I had to switch from “Seq” to “Seq[Any]”. The “=>” differentiates the arguments (on the left, in parens) from the return type (on the right). The reason for this is that the type inference algorithm isn’t set up to handle this – while this is a simple example, recursion that bounces back and forth between two functions is likely too much for the compiler to handle, especially when you might be returning different types through many paths.

Exit mobile version