This week's book giveaway is in the Agile and Other Processes forum. We're giving away four copies of Darcy DeClute's Scrum Master Certification Guide: The Definitive Resource for Passing the CSM and PSM Exams and have Darcy DeClute on-line! See this thread for details.
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.