Search code examples
scalacontinue

How to use continue keyword to skip to beginning of a loop in Scala


How to use continue keyword to skip to beginning of a loop in 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
    }
}

I know there is breakable and break abstracts provided by Scala but that doesn't seem to achieve my functionality.


Solution

  • In functional programming recursion is kind of loop, so consider the following approach

    @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
    }