Checking compilation time in Groovy

Groovy types are optional, so you can use:

String foo = "foo"
foo.noSuchMethod()

or

def foo = "foo"
foo.noSuchMethod()

I assumed that in the first example a compile-time error will be generated, while the second will only work at runtime. However, this does not seem to be the case. In my experience, a compilation error is not generated in any case.

Do I correctly assume that the only advantage of a link type declaration is the documentation form, i.e. communicate intentions to other programmers. For example, if I write a method, for example:

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

Tells the type of arguments that should be passed to the function much more efficiently than:

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

Does the Groovy compiler do type checking when specifying types?

Thanks Don

+3
source share
4

[] Groovy . , , , Groovy, .

, - , , Groovy , Java ( ).

, , ? Groovy, , - , noSuchMethod(). , . , , , .

, ? , , , . , , .

+3

Groovy . , , , , , , , .

+2

Groovy .

String foo = "foo"
foo.noSuchMethod()

,

String.metaClass.noSuchMethod { -> println "Yes there is such a method"}
+2

, , - IDE .

def foo
foo.[ctrl-space]

...

List foo
foo.[ctrl-space]

... may (depending on the IDE) give you a choice of List methods. Of course, a method that is not one of the options may be valid for use, for the reasons indicated in the other answers.

There are other automatic software maintenance operations that benefit from type hints. For example, refactoring.

+1
source

Source: https://habr.com/ru/post/1709700/


All Articles