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

fre*_*low 2 scala type-inference return-type infinite-loop

这是一个人工玩具示例,演示了我的问题:

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
  }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能帮助编译器理解这个方法总会返回一个Int

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

Ion*_*tan 6

总是返回Int:

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