Search code examples
xtend

How to leave a void method at an arbitrary point in Xtend


I want to do a very simple thing in Xtend and don't know how. I have a method with return type void. At the beginning of the method a check a condition and want to leave the method, if the condition is not fulfilled, otherwise proceed. Here is an extract from the code:

def private void generateODB(BlockDeclaration block) {
   val relevantTypes = block.nestedElements.filter[...]

   // nothing to do: leave!
   if (relevantTypes.empty)
      return

   // ...otherwise do some business logic
}

However, I get the exception "Void methods cannot return a value." for the return statement. I can, of course, make a huge if block around the rest of the method body, but isn't it possible just to leave the method at this point? What's the proper syntax in Xtend?


Solution

  • We really should give a better error message about what's wrong here. The problem here is, that

    someCode
    if (somePredicate) 
       return
    someOtherCode
    

    is interpreted as

    someCode
    if (somePredicate) 
       return someOtherCode
    

    So the compiler complains about the result of someOtherCode being returned.

    Add a semicolon or a block to tell the compiler what you mean: I.e.: if (somePredicate) { return } or: if (somePredicate) return;