ZenBalance
ZenBalance

Reputation: 10307

Two type declarations for a single variable in Groovy?

While reading the tutorial on Gradle plugins, I cam across the following code:

apply plugin: GreetingPlugin

greeting.message = 'Hi from Gradle'

class GreetingPlugin implements Plugin<Project> {
    void apply(Project project) {
        // Add the 'greeting' extension object
        project.extensions.create("greeting", GreetingPluginExtension)
        // Add a task that uses the configuration
        project.task('hello') << {
            println project.greeting.message
        }
    }
}

class GreetingPluginExtension {
    def String message = 'Hello from GreetingPlugin'
}

My understanding is that the line def String message = 'Hello from GreetingPlugin' is declaring two types (both a generic def type and a specific String type). Removing either of the types seems to allow the script to continue to execute.

Is there any reason why Groovy allows for two type declarations to be made for a single variable? If so, what are the use cases for this language feature and does it serve a specific purpose in this situation?

Upvotes: 0

Views: 407

Answers (2)

superEb
superEb

Reputation: 5673

Use def when you don't care about limiting the variable to a specific type, e.g. if the variable needs to support different types at runtime. Otherwise, you can omit def and specify a type. There is no benefit to using both.

Read about the semantics here: http://groovy.codehaus.org/Scoping+and+the+Semantics+of+%22def%22

Upvotes: 1

tim_yates
tim_yates

Reputation: 171084

The line

def String message = 'Hello from GreetingPlugin'

is wrong. The def is a waste of characters in this situation as it doesn't do anything

That line is the same as

String message = 'Hello from GreetingPlugin'

See the Def and type section in this page

Upvotes: 3

Related Questions