考虑以下递归函数:
def example (param: List[Int]): Int = { case Nil => 0 case x :: xs => example(xs) }
这会导致以下错误:
type mismatch; [error] found : List[Any] [error] required: List[Int]
从参数声明中可以清楚地看出,分解的结果将是a Int
和a List[Int]
,但显然编译器并不这么认为.我怎样才能做到这一点?
你错过了参数匹配声明.试试这个:
def example (param: List[Int]): Int = param match { case Nil => 0 case x :: xs => example(xs) }