Should we or should we not define the datatype of a variable or return type of a method if we know the datatype and also it is not going to change at runtime? What are the pros and cons or using def vs actual datatype?
One example being, if abc is intended to be List<String>
List<String> abc = "xyz"; //IntelliJ IDEA gives syntax highlighting for improper assignment
def abc = "xyz"; //IntelliJ IDEA will not give syntax highlighting
The def keyword is used to define an untyped variable or a function in Groovy, as it is an optionally-typed language.
Groovy Programming Fundamentals for Java Developers For variable definitions it is mandatory to either provide a type name explicitly or to use "def" in replacement. This is required by the Groovy parser.
def is an alias for Object , so the first 2 signatures are identical. the difference between the 1st two and the 3rd is, that you can return null or an instance of any class from the 1 and 2, whereas you can return only null from the 3rd one.
The @Newify transformation annotation allows other ways to create a new instance of a class. We can use a new() method on the class or even omit the whole new keyword. The syntax is copied from other languages like Ruby and Python.
It's easy to fall into the trap of using def
everywhere, due to convenience (especially if coming from Java)
But as you have seen, if you know the type of something, it's better to type it, especially on public methods. Benefits include; self documentation, ide hints, sanity...
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