Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: for loop until condition

How can I run for until a condition is met? Instead of using scala.util.control.Breaks.break, is it possible to test for a condition within for?

for(line <- source.getLines) {
        if (line.equals("")) scala.util.control.Breaks.break
        Console print "Message> "
        dataWriter.write(line, InstanceHandle_t.HANDLE_NIL)
      }
    } catch  {
        case e: IOException =>{
like image 453
Hanxue Avatar asked Jul 03 '26 03:07

Hanxue


1 Answers

Try takeWhile

for(line <- source.getLines.takeWhile(!_.isEmpty)) {
  Console print "Message> "
  dataWriter.write(line, InstanceHandle_t.HANDLE_NIL)
}

or

source.getLines.takeWhile(!_.isEmpty).foreach {
  line => 
   Console print "Message> "
   dataWriter.write(line, InstanceHandle_t.HANDLE_NIL)
}
like image 123
tiran Avatar answered Jul 05 '26 18:07

tiran