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.

If you want a good book on Scala, take a look at Programming Scala (I'm currently reading through this).

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *