Scala:for循环直到条件

时间:2013-11-25 07:32:55

标签: scala for-loop conditional-statements

如果满足条件,我该如何运行for?而不是使用scala.util.control.Breaks.break,是否可以测试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 =>{

1 个答案:

答案 0 :(得分:8)

尝试takeWhile

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

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