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

后端 未结 6 2059
感情败类
感情败类 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:40

    Based on senia, elbowich and dave's solutions I used following:

    @annotation.tailrec
    def retry[T](availableRetries: Int)(action: => T): T = {
      try {
        return action
      } catch {
        case e: Exception if (availableRetries > 0) => { }
      }
      retry(availableRetries - 1)(action)
    }
    

    Which can be then used as elbowich and dave's solutions:

    retry(3) {
      // some code
    }
    

提交回复
热议问题