I wanted to recursively collect any's strings into a list, so i
generalized from the above and wrote:
The following compile error occurred:
found : String required: List[Any]
case s:String=> s :: recurs(a.tail)
I am not sure what this error message is telling me. It is the
basic question I am putting forward to this forum.
I corrected the compilation problem with the following; but I am unsure
as to why this worked:
Of course, I now get a runtime exception 'ExceptionInInitializerError'.
When the 'any' list is empty, then the execution of 'a.head'
throws the exception. Easily fixed.
Garrett's way is definitely the best, but in answer to the original question:
You get the error because you're trying to get the head of an empty List. You can tackle this firstly by explicitly checking for an empty List, viz: or, more idiomatically, matching on the list itself:
Notice I've put the return type as List[String]. You could leave it as List[Any], but why not make it a List of Strings since you can.
Contrary to what Raymond Tong says, there is no problem in matching a String by type in a List[Any]. This is the point of matching by type.