Scala替代无限循环

Ioa*_*nna 3 scala

在Scala中是否有更多功能替代无限循环?

while(true) {
  if (condition) {
    // Do something
  } else {
    Thread.sleep(interval);
  }
}
Run Code Online (Sandbox Code Playgroud)

Sle*_*idi 8

你可以递归地做

@tailrec
def loop(): Nothing = {
 if (condition) {
  // Do something
  } else {
  Thread.sleep(interval);
  }
  loop()
 }
Run Code Online (Sandbox Code Playgroud)

  • 我认为[`Nothing`](http://scala-lang.org/api/current/scala/Nothing.html)将是更合适的类型.[`Unit`](http://scala-lang.org/api/current/scala/Unit.html)是不返回任何值的东西的类型.`Nothing`是永不返回的东西的类型. (2认同)

ste*_*ino 5

你可以做的一件事就是使用更高阶的函数,Stream.continually并将其与for理解配对:

import scala.util.Random
import scala.collection.immutable.Stream.continually

def rollTheDice: Int = Random.nextInt(6) + 1

for (n <- continually(rollTheDice)) {
  println(s"the dice rolled $n")
}
Run Code Online (Sandbox Code Playgroud)

由于非参考透明的nextInt方法,这个例子本身并不是纯粹的功能,但是它可能有助于你思考函数组合而不是使用副作用.