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

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

    The compiler isn't smart enough to know that you can't exit the while loop, unfortunately. It's easy to trick, though, even if you can't sensibly generate a member of the return type--just throw an exception.

    def process(): String = {
      while (true) {
        ...
      }
      throw new Exception("How did I end up here?")
    }
    

    Now the compiler will realize that even if it escapes the while loop, it can't return a value there, so it doesn't worry that the while loop has return type Unit (i.e. does not return a value).

提交回复
热议问题