Home Method arguments with and without def keyword
Reply: 1

Method arguments with and without def keyword

Sebastian Barth
1#
Sebastian Barth Published in 2018-02-08 10:46:55Z

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
tim_yates
2#
tim_yates Reply to 2018-02-08 11:17:10Z

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...

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.308453 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO