Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 783
Anthony Avatar asked May 02 '13 15:05

Anthony


People also ask

How do you call a method in Groovy?

In Groovy, we can add a method named call to a class and then invoke the method without using the name call . We would simply just type the parentheses and optional arguments on an object instance. Groovy calls this the call operator: () . This can be especially useful in for example a DSL written with Groovy.

What is Groovy method?

More Detail. A method is in Groovy is defined with a return type or with the def keyword. Methods can receive any number of arguments. It's not necessary that the types are explicitly defined when defining the arguments. Modifiers such as public, private and protected can be added.

What is this in Groovy?

" this " in a block mean in Groovy always (be it a normal Java-like block or a Closure) the surrounding class (instance). " owner " is a property of the Closure and points to the embedding object, which is either a class (instance), and then then same as " this ", or another Closure.

Does Groovy return last statement?

The last line of a method in Groovy is automatically considered as the return statement.


1 Answers

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.

like image 89
Erik Pragt Avatar answered Nov 16 '22 20:11

Erik Pragt