14 Sep 2010, 02:48
Generic-user-small

Steve Zhang (22 posts)

Now I am running the Simulate.groovy in chapter 5, page 97: code link: http://media.pragprog.com/titles/vslg/code/UsingClosures/Simulate.groovy

class Equipment
{
  def calculator
  
  Equipment(calc) { calculator = calc }
  
  def simulate()
  {
    println "Running simulation"
    calculator() // You may send parameters as well
  }
}

eq1 = new Equipment() { println "Calculator 1" }

aCalculator = { println "Calculator 2" }

eq2 = new Equipment(aCalculator)
eq3 = new Equipment(aCalculator)

eq1.simulate()
eq2.simulate()
eq3.simulate()

But the Groovy compiler failed, and it throws an exception:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
/Users/steve/dev/groovy/Simulate.groovy: 14: unexpected token: println @ line 14, column 26.
   	eq1 = new Equipment( ) { println "Calculator 1" }
                                          ^

1 error

My Environment is 1.7.4, JVM 1.6.0_20

I feel that Groovy compiler could not recognize the closure when it is in the constructor, the groovy compiler thinks it try to call the default constructor.

14 Sep 2010, 02:53
Generic-user-small

Steve Zhang (22 posts)

I just made a small modification, this time it works:

class Equipment
{
	def calculator
	
	Equipment(){}
	
	Equipment(calc)
	{  
		calculator = calc 
	}
	
	def simulate()
	{
		println "Running simulation"
		calculator()
	}
}	
	
	eq1 = new Equipment() 
	eq1.setCalculator() { println "Calculator 1" }
	
	aCalculator =   { println "Calculator 2" }
    eq2 = new Equipment(aCalculator)
    eq3 = new Equipment(aCalculator)

    eq1.simulate()
    eq2.simulate()
    eq3.simulate()

So I understand that the problem is in the constructor, we might need be careful to use closure behind the constructor, it will confuse the groovy compiler.

This issue needs to be fixed in the next version.

  You must be logged in to comment