如何使用 continue 关键字跳到 Scala 中循环的开头
How to use continue keyword to skip to beginning of a loop in Scala
Scala 中如何使用 continue 关键字跳到循环开头?
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 提供了 breakable 和 break abstracts,但这似乎无法实现我的功能。
在函数式编程中,递归是一种循环,因此请考虑以下方法
@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
}
How to use continue keyword to skip to beginning of a loop in Scala?
Scala 中没有 continue
关键字,因此您不能使用 continue
关键字跳到 Scala 中循环的开头,也不能将其用于其他任何事情,因为您不能使用不存在的东西。
Scala 中如何使用 continue 关键字跳到循环开头?
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 提供了 breakable 和 break abstracts,但这似乎无法实现我的功能。
在函数式编程中,递归是一种循环,因此请考虑以下方法
@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
}
How to use continue keyword to skip to beginning of a loop in Scala?
Scala 中没有 continue
关键字,因此您不能使用 continue
关键字跳到 Scala 中循环的开头,也不能将其用于其他任何事情,因为您不能使用不存在的东西。