Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy: "def" keyword vs concrete type

Tags:

groovy

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
like image 514
Shikhar Avatar asked Nov 27 '16 02:11

Shikhar


People also ask

What is def keyword in Groovy?

The def keyword is used to define an untyped variable or a function in Groovy, as it is an optionally-typed language.

Is def mandatory in Groovy?

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.

What is def in Grails?

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.

What is new keyword in Groovy?

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.


1 Answers

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

like image 196
tim_yates Avatar answered Sep 22 '22 08:09

tim_yates