user786045
user786045

Reputation: 2568

Is there a way to break out of @tailrec in Scala?

I have a method that is recursive. Is there a way in scala to break out based on the size of the buffer (as shown below)? A case for breaking out when elementList.size > 5 for example?

val elementList = ListBuffer.empty[Book]
@tailrec
def getBooks(elements: List[Element]) {
  elements match {
    case Nil => info("Reached end of elements list.")
    case element :: rest if element.getElementType == ElementType.BOOK => {
      elementList.append(element.getBook) 
      getLooks(rest)
    }
    case _ => getBooks(elements.tail)
  }
}

Upvotes: 2

Views: 1350

Answers (2)

Beryllium
Beryllium

Reputation: 12998

Genereally speaking you could try to pass down the number of remaining elements in the recursion.

For example:

  def get(list: List[Int], max: Int): List[Int] = {

    @tailrec
    def get(list: List[Int], acc: List[Int], remaining: Int): List[Int] = {
      list match {

        case h :: tail if remaining > 0 =>
          get(tail, h :: acc, remaining - 1)

        case _ =>
          acc
      }
    }

    // Requires reverse() !
    get(list, Nil, max).reverse

As for the accumulator: you could use a buffer instead, to prevent the reverse() at the end.

Upvotes: 0

cmbaxter
cmbaxter

Reputation: 35463

I guess the most simple way would be to just wrap an if statement around your match statement like this:

val elementList = ListBuffer.empty[Book]
@tailrec
def getBooks(elements: List[Element]) {
  if (elementList.size <= 5){
    elements match {
      case Nil => info("Reached end of elements list.")
      case element :: rest if element.getElementType == ElementType.BOOK => {
        elementList.append(element.getBook) 
        getLooks(rest)
      }
      case _ => getBooks(elements.tail)
    }
  }
}

Upvotes: 1

Related Questions