Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala while(true) type mismatch? Infinite loop in scala?

Why following code

def doSomething() = "Something"

var availableRetries: Int = 10

def process(): String = {
  while (true) {
    availableRetries -= 1
    try {
      return doSomething()
    } catch {
      case e: Exception => {
        if (availableRetries < 0) {
          throw e
        }
      }
    }
  }
}

produces following compiler error

error: type mismatch;
 found   : Unit
 required: String
             while (true) {
             ^

?

This works ok in C#. The while loops forever, so it cannot terminate, therefore it cannot result something else than string. Or how to make infinite loop in Scala?

like image 295
TN. Avatar asked May 29 '12 16:05

TN.


1 Answers

Functional way to define an infinite loop is recursion:

@annotation.tailrec def process(availableRetries: Int): String = {
  try {
    return doSomething()
  } catch {
    case e: Exception => {
      if (availableRetries < 0) {
        throw e
      }
    }
  }
  return process(availableRetries - 1)
}

elbowich's retry function without inner loop function:

import scala.annotation.tailrec 
import scala.util.control.Exception._ 

@tailrec def retry[A](times: Int)(body: => A): Either[Throwable, A] = { 
  allCatch.either(body) match { 
    case Left(_) if times > 1 => retry(times - 1)(body) 
    case x => x 
  } 
} 
like image 173
senia Avatar answered Oct 03 '22 22:10

senia