Search code examples
scalaruntimeexceptionnosuchelementexception

Runtime Exception during executing a function


I am trying to run a function in 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)
}

When I try to run like this,

sum(List(1,2,3))

I am getting the runtime exception

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

On the other hand, this works

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

Solution

  • List(1,2,3) is equivalent to 1::2::3::Nil

    so your function is evaluated in following order

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

    and at last sum(Nil) throws exception.

    You can get more information from following question.

    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?