The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

fiallega (9) [Avatar] Offline
#1
When reading Chapter 3 page 70 it says "Groovy enforces the Java type system! But it only does so at runtime". This statement brought up quite a bit of discussion among some friends.
why can't groovy pick the following error at compile time:

Date myDate = "hello world"

I have been able to explain why it can't when doing the assignment using the String constructor

Date myDate
String.metaClass.constructor = {String s -> new Date()}
myDate = new String("hello")

Is there something similar when doing
Date myDate = "hello world"
that would explain why it can not be caught at compile time
or the compiler is just not smart enough ?

Mittie (397) [Avatar] Offline
#2
Re: no errors at compile time
Hi Jorge,

at the moment, I see now way that

Date myDate = "hello"

could ever succeed at runtime, since the casting logic is fixed in DefaultTypeTransformation.castToType(). The next best you could achieve is enforced type coercion like so

String.metaClass.asType = { Class clazz-> new Date()}
Date myDate = "hello world" as Date

The Groovy compiler _could_ pick up many more errors, but it currently doesn't bother. The information is available, though, and used by tools like CodeNarc and IntelliJ IDEA inspections.

One of the considerations is to make the compiler fast. Unlike Java, the performance of the Groovy compiler is important, especially in the cases where Groovy source code gets executed (i.e. compiled and run) while the application is running: business rules, configurations, formulae, user input, etc.

thanks for posting
Dierk
fiallega (9) [Avatar] Offline
#3
Re: no errors at compile time
waoooo. Great.
Thanks a lot for the explanation. It is very very very much appreciated.