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

后端 未结 6 2049
感情败类
感情败类 2021-02-14 21:01

Why following code

def doSomething() = \"Something\"

var availableRetries: Int = 10

def process(): String = {
  while (true) {
    availableRetries -= 1
    tr         


        
6条回答
  •  庸人自扰
    2021-02-14 21:55

    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 
      } 
    } 
    

提交回复
热议问题