Like Javascript, semicolons are optional in Groovy except for when they aren't optional. These examples are both pretty contrived, though I found both because they're actually something that I've written, and could both be written better. That's not really the point I'm making though. When something doesn't compile when it looks like it clearly should sometimes it's hard to track down why, and it's surprising to learn that it's because you need a semicolon.
Example the first: Generics at the end of a line:
If you try to compile this in Groovy it will give you the error message: 'unexpected token: println', however this:
Example the second: Ambiguous Closures
I don't think you'd really ever need to do something like this, but a closure can be defined and called on a single line. Because of Groovy's special closure parameter syntax (e.g. list.each() {} being synonomous with list.each({})) the compiler thinks I'm passing the second closure into the first as an argument. Again a semicolon is needed to seperate the two lines:
Example the first: Generics at the end of a line:
def list = [1,2,3] as List<Integer>
println list
If you try to compile this in Groovy it will give you the error message: 'unexpected token: println', however this:
Gives the expected output.def list = [1,2,3] as List<Integer>;
println list
Example the second: Ambiguous Closures
{-> assert GroovyClosureTest == owner.getClass() }()
{-> assert GroovyClosureTest == delegate.getClass() }()
I don't think you'd really ever need to do something like this, but a closure can be defined and called on a single line. Because of Groovy's special closure parameter syntax (e.g. list.each() {} being synonomous with list.each({})) the compiler thinks I'm passing the second closure into the first as an argument. Again a semicolon is needed to seperate the two lines:
{-> assert GroovyClosureTest == owner.getClass() }();
{-> assert GroovyClosureTest == delegate.getClass() }()
0 TrackBacks
Listed below are links to blogs that reference this entry: Groovy, sometimes you still need a semicolon..
TrackBack URL for this entry: http://www.nearinfinity.com/mt/mt-tb.cgi/643



Leave a comment