匹配列表后修复类型擦除

时间:2015-12-04 16:54:35

标签: scala pattern-matching

考虑以下递归函数:

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

这会导致以下错误:

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

从参数声明中可以清楚地看出,分解的结果将是IntList[Int],但显然编译器并不这么认为。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:5)

你错过了参数匹配声明。试试这个:

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

答案 1 :(得分:1)

如接受的答案所示,您在param match之后遗漏了=。或者,您可以通过将param match定义为函数值来避免example部分:

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

具有case语句的块被编译器视为匿名函数。