scope - Groovy: What's the difference between defining a variable without "def" versus using anchoring? -


i'm learning groovy , bumped don't understand , hope you'd able shed light.

in regard following example:

import groovy.transform.field   @field list awe = [1, 2, 3]   def awesum() { awe.sum() }   assert awesum() == 6 

i understand anchoring allows me change scope of awe variable being run @ method level of script class level of script.

but think difference between defining variables def or without, example:

def var = "foo" 

and

var = "foo" 

as far understand difference between 2 examples difference of scope. when assign value variable without "def" or other type, in groovy script, it's added "binding", global variables script. means can accessed functions within script.

so taking consideration both "@field" , defining variable without using "def" , following line of thought i've changed example code this:

import groovy.transform.field   awe = [1, 2, 3]   def awesum() { awe.sum() }   assert awesum() == 6 

and works.

so question why use anchoring? if can achieve same goal defining variable without "def"?

you do not achieve same goal - see difference below

import groovy.transform.field awe = [1, 2, 3] def awesum() { awe.sum() } assert awesum() == 6 awe = 1 

work fine variable dynamically typed. on contrary fails

import groovy.transform.field @field list awe = [1, 2, 3] def awesum() { awe.sum() } assert awesum() == 6 awe = 1 

as variable strong typed (java.util.arraylist)

caught: org.codehaus.groovy.runtime.typehandling.groovycastexception: cannot cast object '1' class 'java.lang.integer' class 'java.util.list' org.codehaus.groovy.runtime.typehandling.groovycastexception: cannot cast object '1' class 'java.lang.integer' class 'java.util.list'         @ fieldtest1.run(fieldtest1.groovy:5) 

Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -