0

I have this code:

class myFunc{
  def summatory(list: List[Int]): Int= list match{
    case Nil => 0
    case _ => list(1) + summatory(list.tail)
  }
}

But I'm getting this error: "scalac -classpath . -d . main.scala scala -classpath . Main java.lang.IndexOutOfBoundsException: 1"

How can I solve it?

1
  • You don't know if the list will have two elements, you want to use 0 rather than 1 to access the first element. Although, you may rather call head and avoid that accident again, or even better you use proper pattern matching: case head :: tail => head + summatory(tail) Commented Oct 24, 2022 at 13:30

1 Answer 1

3

Collection indexes in Scala a zero-based, so quick fix would be to just use element at 0 index (otherwise your code will fail on the recursive call processing the last element):

case _ => list(0) + summatory(list.tail)

But better just use pattern matching:

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

Or in particular case of sum - just use sum:

def summatory(list: List[Int]): Int = list.sum
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.