3

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 =>{
3
  • 3
    You should use takeWhile like this: for(line <- source.getLines.takeWhile{_ != ""}) Commented Nov 25, 2013 at 7:45
  • Thanks @senia ! Is it safe to use != to compare Strings, instead of !equals("")? Commented Nov 25, 2013 at 7:54
  • 1
    Yes. In scala == is a null-safe equivalent of equals (it calls equals). There is another operator for reference equality (and you don't need it). Commented Nov 25, 2013 at 7:57

1 Answer 1

8

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)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.