Anthony
Anthony

Reputation: 35988

What would be the return type of this method in groovy?

I have a method such as this:

def getInformation ()  {

  return [true, "reason why"]
}

which I'm using like this

def (isClear, reason) = getInformation()

Is there way to define a return type for this method so its better to read when someone is going through the method?

Upvotes: 25

Views: 93383

Answers (4)

Mr. Cat
Mr. Cat

Reputation: 3552

Anthony, better in your case to return a map [isClear:true, reason:"reason why"]. Then in your code get values:

Map getInformation ()  {
  return [isClear:true, reason:"reason why"]
}
...
def result =  getInformation ()
if(result.isClear){
   ...
   result.reason
   ...
}

Upvotes: 11

Dónal
Dónal

Reputation: 187399

Is there way to define a return type for this method so its better to read when someone is going through the method?

Not really, you could change it to this, but it's not much better:

List getInformation ()  {
  return [true, "reason why"]
}

However, you can define the types of the variables that are assigned the return values, which makes that part of the code more readable.

def getInformation ()  {    
  return [true, "reason why"]
}

def (boolean isClear, String reason) = getInformation()    

Upvotes: 7

Erik Pragt
Erik Pragt

Reputation: 14657

The real return type of this method is Object, since you declared it using 'def'. This means it can return anything, regardless of the object you're actually returning.

The following code would be just as valid:

def getInformation ()  {    
  return "this is some information"
}

or

def getInformation ()  {    
  return 42
}

But the returntype of the method hasn't changed.

The real question here is: why would you choose such an approach? In my opinion, the following would make things so much more clear:

Result getInformation() {
     return new Result(success: true, reason: "why")
}

This would make it much more clear to the caller, and the only thing you'd need to create is a trivial class:

class Result {
     boolean success
     String reason
}

Now you've got a clearly defined API. I would never use def in a method signature, because of the problem you're facing here.

Upvotes: 32

fabiangebert
fabiangebert

Reputation: 2623

The return type will be List, more exactly ArrayList with two elements of type Boolean, String

And as a generic List can only be of a single type (in this case Object), there is no way you can define several return types.

Upvotes: 8

Related Questions