Scala while(true)类型不匹配? Scala中的无限循环? [英] Scala while(true) type mismatch? Infinite loop in scala?

查看:102
本文介绍了Scala while(true)类型不匹配? Scala中的无限循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么要遵循代码

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

产生以下编译器错误

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

?

这在C#中可以正常工作. while会永远循环,因此它无法终止,因此除了字符串以外,它不会导致其他任何结果.还是如何在Scala中进行无限循环?

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?

推荐答案

基于 senia elbowich dave 的解决方案I使用以下:

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

然后可以将其用作elbowich和dave的解决方案:

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

retry(3) {
  // some code
}

这篇关于Scala while(true)类型不匹配? Scala中的无限循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆