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

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

    edit: I just noticed the actual return statement. The return statement inside the while loop will be ignored. For example, in the REPL:

    scala> def go = while(true){return "hi"}
    :7: error: method go has return statement; needs result type
       def go = while(true){return "hi"}
                            ^  
    

    You told the compiler that the process() method returns a String, but your method body is just a while loop, which doesn't return anything (it's a Unit, or a Java void). Either change the return type or add a String after the while loop.

    def process(): Unit = {
       while(true){...}
    }
    

    or

    def process(): String = {
      while(true){...}
      "done"
    }
    

提交回复
热议问题