Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compile-time checking in Groovy

Tags:

types

grails

In Groovy types are optional so you can use either:

String foo = "foo"
foo.noSuchMethod()

or

def foo = "foo"
foo.noSuchMethod()

I assumed that the first example would generate a compile-time error, whereas the second would only fail at runtime. However, this doesn't appear to be the case. In my experience, a compile-time error is generated in neither case.

Am I right in assuming then that the only benefit of declaring the type of a reference is as a form of documentation, i.e. to communicate intentions to other programmers. For example, if I write a method such as:

def capitalize(String arg) {
    return arg.toUpperCase()
}

This communicates the type of arguments that should be passed to the function much more effectively than:

def capitalize(def arg) {
    return arg.toUpperCase()
}

Does the Groovy compiler perform any type-checking when types are specified?

Thanks, Don

like image 219
Dónal Avatar asked Feb 28 '23 16:02

Dónal


2 Answers

[Edit] Newer versions of Groovy do allow for compile-time static type checking. Code that uses this annotation IS faster than regular run-time Groovy, as many of the dynamic checks are skipped.

As Cesar said, type checking is a run-time process, one of the major reasons that Groovy is slower than Java (not that that's really bad).

You can see why this is, right? Given the dynamic nature of Groovy, it's near-impossible to tell if String has been extended somewhere else in your code to contain a method noSuchMethod(). The same goes for member type-checking, as it's entirely possible to remove a member of one type, and add a member of another type with the same name later in code. It's probably not common, but very possible.

The question is, how much type checking do you really need? You're calling the method, you really should know what arguments it takes, or if the method actually exists. Using compile-time checking to save you the time of looking it up isn't a core usefulness of the compiler.

like image 79
billjamesdev Avatar answered Mar 07 '23 10:03

billjamesdev


In Groovy, type checking is done dynamically at runtime. The benefits of variables with type is that you can be sure that it contains the value you expect them to have, otherwise you get a runtime exception that you can catch and do whatever you need to do to handle the exception.

like image 30
Cesar Avatar answered Mar 07 '23 08:03

Cesar