如何使用continue关键字跳至Scala中的循环开头

问题描述 投票:0回答:1

如何使用continue关键字跳至Scala中的循环开始?

while(i == "Y") {
    println("choose an item id between 1 and 4")
    val id = scala.io.StdIn.readInt()
    if(id >= 5) {
        println("not a valid id. please choose again")
        continue
    }
}

我知道Scala提供了易碎和易碎的摘要,但似乎无法实现我的功能。

scala continue
1个回答
1
投票

在函数式编程中,递归是一种循环,因此请考虑以下方法

@tailrec def readInputRecursively(count: Int): Option[Int] = {
  if (count == 0) {
    println("Failed to choose correct id")
    None
  } else {
    println(s"choose an item id between 1 and 4 ($count remaining attempts)")
    val id = StdIn.readInt()
    if (id >= 5) readInputRecursively(count - 1) else Some(id)
  }
}

readInputRecursively(3).map { input =>
  // do something with input
}
© www.soinside.com 2019 - 2024. All rights reserved.