4

I have below code : Which is iterating the arrayList till end even though I don't want it. I don't know how to break it as xtend does not have break statement. Provided I can't convert the same to a while loop, is there any alternative way in xtend similar to break statement in java?

arrayList.forEach [ listElement | if (statusFlag){
     if(monitor.canceled){
          statusFlag = Status.CANCEL_STATUS
          return
     }
     else{
          //do some stuff with listElement
     }      
}]
Stivan
  • 1,128
  • 1
  • 15
  • 24
lifeline2
  • 69
  • 1
  • 15

3 Answers3

4

You can try something like that

arrayList.takeWhile[!monitor.cancelled].forEach[ ... do stuff ...]
if ( monitor.cancelled ) { statusFlag = Status.CANCEL_STATUS }

takeWhile is executed lazily, so it should work as expected and break at correct moment (memory visibility allowing, I hope monitor.cancelled is volatile).

Not sure how status flag comes into picture here, you might need to add check for it in one or both closures as well.

Artur Biesiadowski
  • 3,595
  • 2
  • 13
  • 18
3

You are right, break and continue is not supported by Xtend.

Because it seems that you would like to 'break' based on an external condition (so you can't use e.g. filtering) I think it's not a bad option to throw an exception.

Pseudo code:

try {
    arrayList.forEach[
        if (monitor.canceled) {
            throw new InterruptedException()
        }
        else {
            // Continue processing
        }
    ]
}
catch (InterruptedException e) {
    // Handle
}
snorbi
  • 2,590
  • 26
  • 36
  • thanks snorbi. It is working perfectly and cancels the monitor. But only in debug mode in eclipse with a a debug point at monitor.canceld... During runtime/disabling the debug points,never works in eclipse. Strangely never halts at a debug point if I run the job first then put the debug point too. I am running the monitor inside runInWorkspace() method of eclipse WorkspaceJob. – lifeline2 Sep 28 '16 at 09:43
  • Sorry, I cannot help without the full related code provided. I think that there is a multi-threading problem in your application. I suggest to take a look at how the "volatile" keyword works in Java, or even better you should use concurrency utilities like AtomicBoolean. – snorbi Sep 28 '16 at 10:26
0

You are right, break and continue is not supported by Xtend. Move break specific functionality to java and use that in xtend.

Nagaraj Kandoor
  • 305
  • 5
  • 18