执行函数期间的运行时异常

时间:2017-07-24 05:36:17

标签: scala runtimeexception nosuchelementexception

我正在尝试在scala中运行一个函数

 def sum(xs: List[Int]): Int = xs match {
  case Nil => throw new java.util.NoSuchElementException("Minimum number of elements")
  case x :: xs => x + sum(xs)
}

当我尝试这样跑时,

sum(List(1,2,3))

我收到运行时异常

java.util.NoSuchElementException: Minimum number of elements
  at .sum(<console>:12)
  at .sum(<console>:13)

另一方面,这是有效的

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

1 个答案:

答案 0 :(得分:0)

List(1,2,3)相当于1::2::3::Nil

所以你的功能按照以下顺序进行评估

sum(1::2::3::Nil) = 1 + sum(2::3::Nil)
sum(2::3::Nil) = 2 + sum(3::Nil)
sum(3::Nil) = 3 + sum(Nil)

并且最后sum(Nil)抛出异常。

您可以从以下问题中获得更多信息。

Why is Nil required at the end of a list built using the cons operator

Why do we need Nil while creating List in scala?