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?
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.
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.
" 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.
The last line of a method in Groovy is automatically considered as the return statement.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With