1

Suppose we have the following method:

def myMethodWithParameters(param1, def param2, Object param3) {
    ...
}

What are the differences between using the def keyword and using Object as type for an argument?

What are the differences between using the def keyword and not using any type/keyword for an argument?


What I know so far and does not completely answer the question:

  • def keyword is used to allow dynamic types. So you can even put an Object[] in it.
  • def keyword can be used to make variables available only in current scope instead of globally
Sebastian Barth
  • 4,079
  • 7
  • 40
  • 59

1 Answers1

5

Quick link to the docs which do a good job of explaining this:

When defining a method with untyped parameters, you can use def but it’s not needed, so we tend to omit them. So instead of:

void doSomething(def param1, def param2) { }

Prefer:

void doSomething(param1, param2) { }

But as we mention in the last section of the document, it’s usually better to type your method parameters, so as to help with documenting your code, and also help IDEs for code-completion, or for leveraging the static type checking or static compilation capabilities of Groovy.

The general rule I follow with Groovy, is:

If you know what type you expect, or return, then put that type in the definition. If you only accept String, add the type to the parameter (the same with returning a value). This goes doubly for methods which form part of your "public" API (ie: if other classes or people are going to be making use of the method).

If it's just internal, or accepts a range of value types, then leave the argument untyped, and let Groovy sort it out...

tim_yates
  • 167,322
  • 27
  • 342
  • 338