Skip to main content
 首页 » 编程设计

scala之无限循环似乎混淆了 Scala 的类型系统

2025年12月25日21lyj

这是一个演示我的问题的人造玩具示例:

def sscce(): Int = { 
  val rand = new Random() 
  var count = 0 
  while (true) {   // type mismatch; found: Unit, required: Int 
    count += 1 
    if (rand.nextInt() == 42) return count 
  } 
} 

我如何帮助编译器理解此方法将始终返回 Int

我知道上面的玩具示例可以很容易地重构以完全摆脱无限循环,但我真的希望在我的实际代码中有无限循环。相信我 ;)

请您参考如下方法:

总是返回一个Int:

def sscce(): Int = { 
  val rand = new Random() 
  var count = 0 
  while (true) { 
    count += 1 
    if (rand.nextInt() == 42) return count 
  } 
  count // <-- this 
}