Fix type erasure after matching a list

Consider the following recursive function:

def example (param: List[Int]): Int = {
    case Nil => 0
    case x :: xs => example(xs)
}

This leads to the following error:

type mismatch;
[error]  found   : List[Any]
[error]  required: List[Int]

From the declaration of parameters it should be clear that the result of the decomposition will be an Int and a List[Int], but obviously the compiler does not think so. How can I make this work?

Answers


You have missed param match statement. Try this:

def example (param: List[Int]): Int = param match {
  case Nil => 0
  case x :: xs => example(xs)
}

As the accepted answer indicates, you're missing a param match after the =. Alternately, you can avoid the param match part by defining example as a function value :

val example: List[Int] => Int = {
  case Nil => 0
  case x :: xs => example(xs)
}

The block with case statements is treated as anonymous function by the compiler.


Need Your Help

Update javascript to newest version of JQuery

javascript jquery asp.net gridview

Probably a terrible title but wasn't sure how to state the issue.

Using CGFLOAT_MAX to hide UITableViewCell separator

ios objective-c uitableview

I am trying to hide the separator for a specific UITableViewCell and am using cell.separatorInset = UIEdgeInsetsMake(0.0, CGFLOAT_MAX, 0.0, 0.0);. This causes very weird problems on older devices ...